Search target in unknown-length sorted array
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates algorithm design and implementation skills for search algorithms on array-like interfaces with unknown length, focusing on bounds discovery, handling out-of-bounds sentinels, duplicate elements, and rigorous time and space complexity analysis.
Constraints
- The array is sorted in non-decreasing order.
- Length is unknown; only get(i) may be used to probe (out-of-bounds returns a sentinel).
- Values and the target k fit in a 32-bit signed integer.
- 0 <= conceptual length <= 10^9 (algorithm must not depend on knowing it).
- Duplicates may exist; return the smallest index whose value equals k.
- Return -1 if k is not present.
Examples
Input: ([1, 2, 3, 5, 8, 13, 21], 13)
Expected Output: 5
Explanation: 13 sits at index 5; exponential search overshoots past it, binary search pins the exact index.
Input: ([1, 2, 3, 5, 8, 13, 21], 4)
Expected Output: -1
Explanation: 4 is absent; binary search lands on the first value >= 4 (which is 5), and since 5 != 4 it returns -1.
Hints
- You cannot call len(). To bound the search space, start at index 1 and keep doubling (1, 2, 4, 8, ...) until get(index) is out of bounds OR get(index) >= k. The previous index is a safe lower bound.
- Out-of-bounds probes should behave like +infinity: they are 'greater than or equal to' any target, so binary search pushes them to the right side.
- To return the FIRST occurrence among duplicates, run a 'leftmost' binary search: when value >= k, record the index and keep searching the LEFT half (right = mid - 1).
- After binary search lands on the first index with value >= k, verify that value actually equals k — if it's strictly greater (or out of bounds), k is absent, so return -1.