Implement binary search lower/upper bounds
AmazonApplied Scientist · Technical ScreenLast updated
Implement lower_bound and upper_bound on a non-decreasing sorted array using iterative binary search in O(log n) time and O(1) space. This Amazon ML engineer screen tests precise boundary handling, loop-invariant reasoning, and edge cases like duplicates, empty arrays, and out-of-range targets.
Question
Given a non-decreasing sorted integer array nums of length n and a target value, implement two functions using binary search:
lower_bound(nums, target)— return the smallest indexisuch thatnums[i] >= target. Returnn(i.e.len(nums)) if no such index exists.upper_bound(nums, target)— return the smallest indexisuch thatnums[i] > target. Returnn(i.e.len(nums)) if no such index exists.
Requirements:
- Provide iterative implementations.
- Achieve O(log n) time and O(1) extra space.
- Handle the following edge cases: empty array; all elements strictly less than
target; all elements strictly greater thantarget; duplicate values; negative numbers; and targets that fall outside the array’s value range. - Include a few test cases that demonstrate correctness.
- Briefly argue correctness, explaining your boundary conditions and loop invariants.
Note that upper_bound(nums, target) - lower_bound(nums, target) gives the count of elements equal to target, and both functions return a valid insertion point that keeps the array sorted.
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.