Skip to content
mlmentorship

Binary Search

Find a target in a sorted array.

Published · 11 min read ·Core ·Foundation

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Explain the mechanism, why it works, when it fails, and one alternative.

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.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Preserve the inclusive sorted interval that can still contain target 11.

Problem trace

One comparison discards every sorted value on the wrong side

Worked example: the comparison removes an entire sorted regionFor target 7 in (1,3,5,7,9), middle value 5 is too small. Every value at or left of that middle is also too small.One comparison removes a region, notjust one itemSorted candidates; target seven1031527394Middle five is too small: reject itsentire prefix1031527394Original positions stay fixed;crossed items cannot contain theanswer.
Read it this way: For target 7 in (1,3,5,7,9), middle value 5 is too small. Every value at or left of that middle is also too small. Why can the value three be rejected without comparing it directly with seven?
Full interview answer 11 min read
Reading depth

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

Input and goalFind a target in a sorted array.
Initialize the candidate intervalStart with left=0, right=7 and target 11. The midpoint is index 3, value 4.
left-90-3102middle4374115186right257
target11interval[0, 7]comparison4 < 11
Candidate indices for target 11: 0 through 7. This is the initial candidate range; no earlier state is assumed.Candidate indices; target 1101234567Start4 < 11
left
0
middle
3
right
7

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.
Start with left=0, right=7 and target 11. The midpoint is index 3, value 4. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why can every index through 3 be discarded after inspecting only index 3?
Reference drawing

Problem trace

One comparison discards every sorted value on the wrong side

Worked example: the comparison removes an entire sorted regionFor target 7 in (1,3,5,7,9), middle value 5 is too small. Every value at or left of that middle is also too small.One comparison removes a region, notjust one itemSorted candidates; target seven1031527394Middle five is too small: reject itsentire prefix1031527394Original positions stay fixed;crossed items cannot contain theanswer.
Execution trace
Input and goalFind a target in a sorted array.
Initialize the candidate intervalStart with left=0, right=7 and target 11. The midpoint is index 3, value 4.
left-90-3102middle4374115186right257
target11interval[0, 7]comparison4 < 11
Candidate indices for target 11: 0 through 7. This is the initial candidate range; no earlier state is assumed.Candidate indices; target 1101234567Start4 < 11
left
0
middle
3
right
7

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.
Start with left=0, right=7 and target 11. The midpoint is index 3, value 4. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why can every index through 3 be discarded after inspecting only index 3?
Read it this way: For target 7 in (1,3,5,7,9), middle value 5 is too small. Every value at or left of that middle is also too small. Why can the value three be rejected without comparing it directly with seven?
leftrightmiddle/valueDecision
073 / 4All indices through 3 are too small; set left = 4
475 / 11Return 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:

Position01234
Value1224Sentinel
BoundaryLowerUpper

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.