KatInterview

Leftmost Match in a Sorted Sequence Without a Known Size

Heaps, Sorting & SearchAuto-graded · 23 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searchexponential-searchduplicates

Last updated

Find the first index of a target in a sorted list while the search pretends its length is unknown, using doubling probes followed by a lower-bound binary search.

You are given a list values of integers sorted in non-decreasing order, and an integer target.

Imagine you were only allowed to read the list one position at a time, and reading past the final position yields a "too large" sentinel (as if the value were positive infinity). Under that mindset you would not know the list's size ahead of time, so you cannot simply binary search over [0, len - 1] from the start. Design your algorithm in that spirit: first discover a range that must contain the answer, then search inside it.

Return the smallest index i such that values[i] == target. If the target does not occur in the list, return -1.

Details:

  • The list may contain repeated values. When the target appears several times, return the position of its first (leftmost) appearance.
  • The list may be empty, in which case the answer is -1.
  • The target may be smaller than every element, larger than every element, or fall between two neighbouring elements; in each of these cases where it is not present, return -1.

Aim for a running time of O(log p), where p is the index of the first element that is greater than or equal to target (or the list length if there is none), using O(1) extra space. A linear scan, or measuring the length by walking the list, is not the intended solution.

Constraints

  • 0 <= len(values) <= 10^6
  • values is sorted in non-decreasing order.
  • Each element and target fit in a 32-bit signed integer.
  • Return an integer: the leftmost index of target, or -1 if it is absent.

Examples

Example 1

Input: find_first_occurrence_unbounded([1, 3, 5, 7, 9], 7)

Output: 3

Example 2

Input: find_first_occurrence_unbounded([1, 3, 5, 7, 9], 4)

Output: -1

Example 3

Input: find_first_occurrence_unbounded([1, 2, 2, 2, 4, 8], 2)

Output: 1

Example 4

Input: find_first_occurrence_unbounded([10, 20, 30], 5)

Output: -1

Hints

Hint 1

Without a known length, start with a small window and grow it. Probe positions 1, 2, 4, 8, ... until you reach a value that is at least the target or you step past the end.

Hint 2

Once the doubling stops, the first position holding a value >= target must lie between the previous probe and the current one (clamped to the last valid index). Binary search only that window.

Hint 3

Do not return as soon as you see the target in the binary search. Move the right end to mid when values[mid] >= target so you converge on the leftmost candidate, then verify it equals the target.