Implement binary search from scratch
UberSoftware Engineer · OnsiteLast updated
An Uber software engineer onsite coding question asking you to implement binary search on a sorted integer array from scratch, in both iterative and recursive form. It covers plain search, first/last occurrence with duplicates, the insertion-index variant, overflow-safe midpoint computation, loop invariants and correctness, and time/space complexity analysis.
Question
Implement binary search on a sorted integer array without using any library helpers (no bisect, Arrays.binarySearch, etc.). Provide both iterative and recursive versions, and address each of the following:
- Basic search. Return the index of the target if it is present, or
-1if it is absent. - First occurrence. When the array contains duplicates, return the index of the first occurrence of the target.
- Last occurrence. When the array contains duplicates, also be able to return the index of the last occurrence of the target.
- Insertion index. If the target is absent, return the index at which it could be inserted while keeping the array sorted (the classic "search insert position").
- Integer overflow. Compute the midpoint in a way that avoids integer overflow on large indices.
- Correctness & invariants. Clearly state your loop invariant and boundary handling (inclusive vs. exclusive bounds), and argue why the search terminates and is correct.
- Complexity. State the time and space complexity of each variant.
Example
nums = [1, 2, 2, 2, 5, 7], target = 2
basic search -> any index in {1, 2, 3}
first occ. -> 1
last occ. -> 3
nums = [1, 3, 5, 6], target = 4
basic search -> -1
insertion idx -> 2
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.