Menu
CoddyTech

Find First and Last Position of Element in Sorted Array

MediumBinary searchpython iconjava iconcpp iconc iconjs icon+10

You get a list of integers nums sorted in non-decreasing order, so a value can repeat, and an integer target. Return a list of two indexes, counting from 0: the first and the last position where target appears. If target is not in the list, return [-1, -1]. Aim for O(log n) time.

Function

searchRange(nums: integer-array, target: integer) → integer-array
numsinteger-array
the sorted list of integers, which may repeat values
targetinteger
the value to look for
Returnsinteger-array
the first and the last index of target, or [-1, -1] if it is missing

Constraints

  • 1 ≤ nums.length ≤ 104
  • -104 ≤ nums[i], target ≤ 104
  • nums is sorted in non-decreasing order.

Examples

Input
nums = [3, 5, 5, 5, 8, 9, 9, 12]target = 5
Output
[1, 3]
Explanation
The three copies of 5 sit at indexes 1, 2 and 3, so the run starts at 1 and ends at 3. Index 0 holds 3 and index 4 holds 8, so the run cannot reach further.
challenge icon

Follow-up

If the same list gets thousands of queries for different targets, can one pass over it in advance make each query faster than O(log n)?

Reset code
def searchRange(nums, target):
    # Write code here

Test #1

Test #2

Arguments

nums = [3, 5, 5, 5, 8, 9, 9, 12]
target = 5

Expected Output

[1, 3]