FastPrepFirst and Last Position in a Sorted Array

First and Last Position in a Sorted Array

Apple logoApple● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

The integer array nums is sorted in nondecreasing order. Return the first and last indices containing target.

If the target is absent, return [-1,-1]. Your algorithm must run in O(log n) time, where n is the array length.

Function

searchRange(nums: int[], target: int) → int[]

Examples

Example 1

nums = [5,7,7,8,8,10]target = 8return = [3,4]

The target appears at positions 3 and 4.

Example 2

nums = [5,7,7,8,8,10]target = 6return = [-1,-1]

The target does not occur.

Example 3

nums = []target = 0return = [-1,-1]

An empty array contains no target.

Constraints

  • 0 <= nums.length <= 10^5.
  • -10^9 <= nums[i], target <= 10^9.
  • nums is sorted in nondecreasing order.

More Apple problems

See Apple hiring insights
public int[] searchRange(int[] nums, int target) {
    // Write your solution here.
}
nums[5,7,7,8,8,10]
target8
expected[3,4]
Checking account…