← Questions

Lower and upper bound binary search

0
AmazonCodingLast asked Sep 2025

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) -> int
  • upper_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) with hi = len(nums), looping while lo < hi, mid = lo + (hi - lo) // 2; for lower_bound, nums[mid] < target moves lo = mid + 1, otherwise hi = mid. upper_bound changes only < to <=.
  • The loop invariant stated and used: every index below lo fails the condition, every index from hi on meets it, so lo == hi at the end is the answer.
  • Why hi = len(nums) rather than len(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 d days.
  • 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

binary-search

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