← Questions
Search a sorted array of unknown length
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Amazon's technical phone screen, last asked Sep 2025. It tests binary-search.
A sorted array can only be read through get(i), which returns the value at index i or a sentinel (here None) when i is past the end. You do not know the length and cannot ask for it. Given a target, return the index of its first occurrence, or -1 if it is absent.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
search(reader, target: int) -> int—reader.get(i)is the only access; values are in non-decreasing order and may repeat.
Example
array = [1, 2, 3, 5, 8, 13, 21]
search(reader, 13) -> 5
search(reader, 4) -> -1 # the first value >= 4 is 5, which is not 4
array = [1, 2, 2, 2, 5, 8]
search(reader, 2) -> 1 # the first of the three 2s
search(reader, 9) -> -1 # past every value
Constraints
- The length can be anything from 0 to 10^9.
- Values and the target fit in 32-bit signed integers.
Clarifying questions
- What does
getreturn out of bounds: a sentinel, a very large number, or an exception? - With duplicates, which index: any, the first or the last? (The first.)
- Is the array strictly increasing or only non-decreasing?
What a strong answer covers
- Find a bound by doubling: probe indices 1, 2, 4, 8, … until
getreturns the sentinel or a value at least the target. The previous probe is a safe lower bound. O(log p) probes for target positionp. - Leftmost binary search inside
[lo, hi], treating the sentinel as +infinity: when the value is at least the target, record it and go left. Then check that the value found equals the target. - Total O(log p) time and O(1) space, independent of the array's length.
- Edge cases: an empty array (
get(0)is the sentinel), the target at index 0, the target larger than everything, a long run of duplicates.
Follow-ups
- Return the last occurrence, or the count of occurrences.
- Each
getcall is expensive (a network request). How do you minimise the number of calls? - The array is rotated at an unknown point.
Where it's asked
- Amazon · Technical phone screen · Last asked Sep 202560 min · Live coding in a shared editor that does not run code, plus Leadership Principles questions · No AI
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
