← Questions
Lower and upper bound binary search
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.
Given an array sorted in non-decreasing order and a target, implement two binary searches, both iterative:
-
lower_bound— the first index whose value is at least the target. -
upper_bound— the first index whose value is greater than the target.
Each returns len(nums) when no such index exists, so both are valid insertion points. Their difference is the number of copies of the target.
Interface
Unless you agree on a different interface with the interviewer, assume:
lower_bound(nums: list[int], target: int) -> intupper_bound(nums: list[int], target: int) -> int
Example
nums = [1, 2, 2, 2, 5, 8]
lower_bound(nums, 2) -> 1 upper_bound(nums, 2) -> 4 # three 2s: 4 - 1 = 3
lower_bound(nums, 3) -> 4 upper_bound(nums, 3) -> 4 # absent: both give the insertion point
lower_bound(nums, 0) -> 0 upper_bound(nums, 9) -> 6 # outside the range
lower_bound([], 5) -> 0
Constraints
-
0 <= len(nums) <= 10^5;-10^9 <= nums[i], target <= 10^9. - O(log n) time and O(1) extra space; no recursion.
Clarifying questions
- Should a missing target return
len(nums)or -1? (len(nums).) - May I use the language's library functions? (No.)
What a strong answer covers
- A half-open range
[lo, hi)withhi = len(nums), looping whilelo < hi,mid = lo + (hi - lo) // 2; forlower_bound,nums[mid] < targetmoveslo = mid + 1, otherwisehi = mid.upper_boundchanges only<to<=. - The loop invariant stated and used: every index below
lofails the condition, every index fromhion meets it, solo == hiat the end is the answer. - Why
hi = len(nums)rather thanlen(nums) - 1, and how the off-by-one mistakes cause infinite loops. - Tests: empty array, all smaller, all larger, all equal, duplicates, negative values.
Follow-ups
- Find the first and last position of the target, or -1 if absent.
- Binary search on the answer: the smallest capacity that ships all packages within
ddays. - Search in a rotated sorted array.
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
