Find the position of a requested integer in a sorted list, or report that it is absent.
Problem
Input. A random-access list nums of integers in nondecreasing order and an integer target.
Output. Return a zero-based index whose value equals target, or -1 if no such index exists.
Rules. Do not modify the list. Empty input returns -1.
Duplicates are allowed; any matching index is valid, not necessarily the first.
An unsorted list is outside the contract.
Example. In [-9, -3, 0, 4, 7, 11, 18, 25], target 11 returns 5.
Target 12 returns -1. For [2, 2, 2] and target 2, any index from 0 through 2 is valid.
Picture: Preserve the Inclusive Candidate Interval
Problem trace
Separate worked search: retain the inclusive candidate interval for target 11
- left
- 0
- middle
- 3
- right
- 7
- left
- 0→4
- middle
- 3→5
- interval
- [0, 7]→[4, 7]
- result
- not shown→index 5
- interval
- [4, 7]→not shown
- comparison
- 11 = 11→not shown
- Recognize it
- The input is sorted and the task asks for an exact target position, so comparing one middle value can order the target relative to an entire half.
- Keep true
- Before every probe, if target 11 exists, its index is inside the inclusive interval [left, right]; every removed index is provably too small or too large.
- Reuse it
- For lower-bound, upper-bound, and insertion-position variants, first define what the interval promises, then choose whether middle is excluded or retained after each comparison.
Reference drawing
Problem trace
One comparison discards every sorted value on the wrong side
Execution trace
- left
- 0
- middle
- 3
- right
- 7
- left
- 0→4
- middle
- 3→5
- interval
- [0, 7]→[4, 7]
- result
- not shown→index 5
- interval
- [4, 7]→not shown
- comparison
- 11 = 11→not shown
- Recognize it
- The input is sorted and the task asks for an exact target position, so comparing one middle value can order the target relative to an entire half.
- Keep true
- Before every probe, if target 11 exists, its index is inside the inclusive interval [left, right]; every removed index is provably too small or too large.
- Reuse it
- For lower-bound, upper-bound, and insertion-position variants, first define what the interval promises, then choose whether middle is excluded or retained after each comparison.
| left | right | middle/value | Decision |
|---|---|---|---|
| 0 | 7 | 3 / 4 | All indices through 3 are too small; set left = 4 |
| 4 | 7 | 5 / 11 | Return 5 |
Invariant: if a target exists, a matching index remains in [left, right].
If nums[middle] < target, every earlier value is too small; the opposite comparison removes middle and larger indices.
Every miss removes middle, strictly shrinking the interval. left > right means no candidates remain.
Code
def binary_search(nums: list[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
middle = (left + right) // 2
if nums[middle] == target:
return middle
if nums[middle] < target:
left = middle + 1
else:
right = middle - 1
return -1
With ordinary comparison/random-access costs, time is and auxiliary space is .
[] returns -1 immediately. [2, 2, 2], target 2, returns 1: correct for any-match, not first-match.
Change 1: First Value at Least the Target
New task. Return an insertion boundary, including when no equality exists.
Picture and change. Use unknown elements [left, right). Values before left are too small; values from right qualify.
The possible boundary includes right, so equality keeps middle as a boundary candidate.
Code.
def lower_bound(nums, target):
left, right = 0, len(nums)
while left < right:
middle = (left + right) // 2
if nums[middle] < target:
left = middle + 1
else:
right = middle
return left
Check. [1, 2, 2, 4], target 2, returns 1; target 5 returns 4; empty input returns 0.
Use when. The answer is the first >= target position. len(nums) is a valid sentinel, not an index to read.
Change 2: First Value Strictly Greater
New task. Insert after every equal value.
Picture and change. Values before left are now <= target; values from right are greater. Equality moves left.
Code.
def upper_bound(nums, target):
left, right = 0, len(nums)
while left < right:
middle = (left + right) // 2
if nums[middle] <= target:
left = middle + 1
else:
right = middle
return left
Check. [1, 2, 2, 4], target 2, returns 3; upper minus lower is duplicate count 2.
Use when. Equality belongs on the discarded left side.
Failure: Mixing Interval Conventions
Keeping while left <= right but changing to right = middle can repeat the singleton state forever.
Transfer Check
Why does lower bound retain an equal middle as a possible answer?
Reasoned Answer
It may be the first qualifying position; earlier equal values might remain. Equality alone does not settle this boundary contract.
Draw the Two Boundaries
For [1, 2, 2, 4] and target 2:
| Position | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Value | 1 | 2 | 2 | 4 | Sentinel |
| Boundary | Lower | Upper |
Boundary search classifies a prefix and suffix, not an inclusive interval of unread array elements.
When its half-open unknown interval empties, left == right is the answer boundary.
Each update strictly reduces right - left.
For the incompatible exact-search change, (left, right) = (0, 0) and right = middle = 0 makes no progress.
Re-prove both preservation and termination whenever endpoint meaning changes.
Unsorted input invalidates the half-deletion argument. Duplicate handling must follow the required output, not a remembered template.