KatInterview

Locate the Span of a Value in a Sorted List

Heaps, Sorting & SearchAuto-graded · 21 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searcharraysbisect

Last updated

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

Locate the Span of a Value in a Sorted List

You are given a list of integers values sorted in non-decreasing order (duplicates are allowed) and an integer key.

Because the list is sorted, all occurrences of key form one contiguous block. Return the zero-based index where this block begins and the zero-based index where it ends (both inclusive), as a list [start, end].

If key does not occur in values, return [-1, -1].

Your solution must run in O(log n) time, where n is the length of the list. A linear scan, or finding one match and then expanding outward, does not meet this requirement.

Input

  • values: a list of integers sorted in non-decreasing order. It may be empty.
  • key: an integer to search for.

Output

  • A list of two integers [start, end], the first and last index at which key appears.
  • [-1, -1] if key is not present.
  • If key appears exactly once, start and end are equal.

Constraints

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

Edge cases to handle

  • An empty list.
  • Every element equals key.
  • key is smaller than every element or larger than every element.
  • key lies between two existing values but is not itself present.

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

Sorted order means all copies of the key are adjacent, so you only need to find the two boundaries of that block.

Hint 2

Write a binary search that returns the first index whose element is >= key. A second search for the first index whose element is > key gives the position just past the block.

Hint 3

After the first search, check that the index is inside the list and that the element there really equals the key. Do this check before reading the element so an empty list does not cause an error.