KatInterview

Find Boundary Indices in Sorted Sequence

Heaps, Sorting & SearchAuto-graded · 20 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searcharrayssearching

Last updated

Adapt binary search to locate the starting and ending index of a target value in a sorted sequence in logarithmic time.

Given a non-decreasingly sorted array of integers nums and a search value target, return a pair of integers representing the inclusive starting and ending index of target in the array. If target does not appear in nums, return [-1, -1].

Your implementation must run in O(log n) time complexity.

Constraints

  • 0 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • nums is sorted in non-decreasing order.
  • -10^9 <= target <= 10^9

Examples

Example 1

Input: search_range([5, 7, 7, 8, 8, 10], 8)

Output: [3, 4]

Example 2

Input: search_range([5, 7, 7, 8, 8, 10], 6)

Output: [-1, -1]

Hints

Hint 1

Standard binary search terminates upon finding any matching index, which could be in the middle of a duplicated sequence. Linear scanning from that point could take O(n) time.

Hint 2

Instead, implement a binary search variant that finds the insertion point (lower bound): the first index where the element is greater than or equal to a given value.

Hint 3

You can find the starting index by searching for `target`. You can find the ending index by searching for `target + 1` and taking the index immediately preceding it.