KatInterview

Locate the Span of a Value in a Sorted List

Heaps, Sorting & SearchAuto-graded · 23 test cases
EasyAuto-gradedHeaps, Sorting & Searchbinary-searchsorted-arrayboundaries

Last updated

Use binary search to find the first and last positions of a value in a sorted list in logarithmic time, returning [-1, -1] when it is absent.

You are given a list of integers values arranged in non-decreasing order, together with an integer needle.

Determine the zero-based position of the earliest element equal to needle and the position of the latest element equal to needle. Return them as a two-element list [first, last].

If needle does not occur anywhere in values, return [-1, -1]. If it occurs exactly once, both entries are the same index.

Requirements

  • The solution must run in O(log n) time, where n is the length of values. Scanning the list linearly, or finding one match and walking outward, is too slow when many elements are equal.

Input

  • values: a list of integers sorted in non-decreasing order (it may be empty).
  • needle: an integer.

Output

  • A list of two integers [first, last], or [-1, -1] if needle is not present.

Constraints

  • 0 <= len(values) <= 10^5
  • -10^9 <= values[i], needle <= 10^9
  • values is sorted in non-decreasing order (duplicates are allowed).

Examples

Example 1

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

Output: [3, 4]

Example 2

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

Output: [-1, -1]

Example 3

Input: find_value_span([], 0)

Output: [-1, -1]

Hints

Hint 1

All copies of the needle form one contiguous block, so you only need the two ends of that block rather than every match.

Hint 2

Binary search can find the first index whose value is at least the needle. A second, similar search finds the first index whose value is strictly greater than the needle.

Hint 3

After the first search, check that the index is inside the list and that the value there equals the needle before trusting it; otherwise the answer is [-1, -1]. The last position is one before the second search's result.