AceYourInterviews
Checking sign-in…

61. First and Last Position of a Target

CoreTwo monotone boundaries for a duplicate range

Find the complete consecutive block occupied by the target in the sorted array. Return the positions at both ends of that block.

Finding one matching occurrence is not enough. Determine both boundaries efficiently without scanning through a potentially large run of equal values.

Example 1

Input

[5,7,7,8,8,10], target=8

Output

[3,4]

Explanation: First >=8 is index 3; first >8 is index 5, so inclusive last is 4.

Example 2

Input

[1,3], target=2

Output

[−1,−1]

Explanation: The lower boundary is 1 but nums[1] is 3; validate equality before reporting a range.

Example 3

Input

[MIN,MAX,MAX], target=MAX

Output

[1,2]

Explanation: An explicit strict upper-bound predicate avoids overflowing MAX+1.

Constraints

  • 0 <= nums.length <= 105
  • -231 <= nums[i] <= 231 - 1
  • -231 <= target <= 231 - 1
  • nums is sorted in nondecreasing order; duplicates are allowed.
Hints
Hint 1

All occurrences are one block. Which two boundaries describe that block?

Hint 2

Find first >=target, then first >target, with no target arithmetic.

Hint 3

Validate the lower boundary, and convert [first,after) into [first,after−1].

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Search both ends of an interior duplicate run

[5,7,7,8,8,10]
8
[3,4]