Binary Search
Common Approaches to Binary Search Questionsβ
Binary search works on anything monotonic, not just sorted arrays: if a condition is false up to some point and true after it, you can find that point in O(log n).
| Pattern | Use when | Template |
|---|---|---|
| Exact match | Sorted, unique values, return the index or -1 | Iterative Binary Search |
| Left border (first β₯ target) | Duplicates, insertion point, "first occurrence" | Find Left Border, or bisect_left |
| Right border (last β€ target) | "Last occurrence", "first strictly greater" | Find Right Border, or bisect_right |
| Search on the answer | Minimise or maximise a value where "x works" implies "x + 1 works" | Binary Search on the Answer |
| Rotated or partially sorted | One half of every split is still sorted | Search In Rotated Sorted Array |
| 2D matrix | Rows sorted and each row starts after the previous ends | Treat it as one array: row, col = divmod(mid, cols) |
Binary Search on the Answerβ
When the question asks for the smallest speed, capacity or time that satisfies a condition, don't search the input. Search the range of possible answers, and test each guess with a greedy feasible(x) check.
Figure BS-2: Koko Eating Bananas with piles [3, 6, 7, 11] and h = 8. Feasibility flips once, from β to β. Amber is the first feasible speed, which is the answer.
def minEatingSpeed(piles, h):
def feasible(k): # can Koko finish at speed k?
return sum((p + k - 1) // k for p in piles) <= h
lo, hi = 1, max(piles) # the answer is somewhere in [lo, hi]
while lo < hi:
mid = (lo + hi) // 2
if feasible(mid):
hi = mid # mid works, but a smaller one might too
else:
lo = mid + 1 # mid fails, so everything below it fails
return lo
Same shape: Capacity To Ship Packages, Split Array Largest Sum, Minimum Days to Make Bouquets. Time is O(n log(range)).
Gotchasβ
| Mistake | Result |
|---|---|
while left <= right with right = len(nums) | β Reads nums[len(nums)]: index out of range |
left = mid in a [left, right) loop | β Infinite loop when right == left + 1 |
| Mixing interval styles in one function | β Off-by-one at the edges. Pick closed [l, r] or half-open [l, r) and keep it |
Python bisect_left / bisect_right | β Border searches for free, when the interviewer allows it |
Iterative Binary Searchβ
This is the common binary search where a sorted array nums is given and we are tasked to find target in that array.
Returns the index of the target if it exist in the array, else returns -1.
Time Complexity: O(logn)
Space Complexity: O(1)
Time complexity is O(logn) as the search range is halved every iteration until target is found. The iterative approach will
give a O(1) space complexity.
Recurrence Relation: T(N) = T(N/2) + O(1)
def binarySearch(nums, target):
left, right = 0, len(nums)
while left < right: # Search interval = [left, right)
mid = (left + right) // 2
if nums[mid] == target: # target found! Return index
return mid
elif nums[mid] < target: # search right -> [mid+1, right)
left = mid + 1
else: # search left -> [left, mid)
right = mid
# Target not found -> return -1
return -1
Search Intervalβ
Every template on this page uses the half-open interval [left, right): left is the first candidate, right is one past the last. The intuition is that right already points at something excluded, so "drop mid and everything after it" is just right = mid.
Half-open [l, r) (default) | Inclusive [l, r] | |
|---|---|---|
init r | len(nums) | len(nums) - 1 |
| loop | l < r | l <= r |
| shrink right | r = m | r = m - 1 |
| shrink left | l = m + 1 | l = m + 1 |
| loop ends when | l == r (interval empty) | l == r + 1 (interval empty) |
| after the loop | l == r is the insertion point | l is the insertion point, r = l - 1 |
Why half-open is the default: the loop exits with l == r, a single answer, and that answer is always a valid insertion point in [0, len]. The same shape works for the exact match, both borders and search on the answer.
Find Left Borderβ
With duplicates, the plain search returns any matching index. The border searches keep going after a match: left border shrinks right onto it, right border pushes left past it.
Figure BS-1: Searching for 2 in [1, 2, 2, 2, 3]. Amber is the run of matches; the two border searches return its ends.
Intuition: the loop keeps two walls. Everything left of l is known to be < target; everything from r onward is known to be >= target. Each step moves one wall to mid, and the loop ends when the walls meet. That meeting point is the first index >= target.
nums[m] vs target | What it tells you | Move |
|---|---|---|
< | m and everything before it is too small | l = m + 1 |
== | m could be the first match, but an earlier one may exist | r = m (keep looking left) |
> | m and everything after it is too big | r = m |
| loop ends | l == r = first index with nums[i] >= target | answer is l |
The == row is the only difference from the plain search: instead of returning, treat a match like "too big" and keep shrinking from the right.
def bsLeftBorder(nums, target):
if not nums:
return -1
left = 0
right = len(nums)
while left < right: # [left, right)
mid = (left + right) // 2
if nums[mid] == target: # [left, mid)
right = mid
elif nums[mid] < target: # [mid + 1, right)
left = mid + 1
elif nums[mid] > target: # [left, mid)
right = mid
print(left) # left => number of elements smaller than target
# If we want to return -1 when target not found
if left >= len(nums) or nums[left] != target:
return -1
return left # returns index of left border
Find Right Borderβ
Intuition: same two walls, shifted by one. Everything left of l is <= target; everything from r onward is > target. The walls meet at the first index > target, so the last match sits one step to its left.
nums[m] vs target | What it tells you | Move |
|---|---|---|
< | m and everything before it is too small | l = m + 1 |
== | m could be the last match, but a later one may exist | l = m + 1 (keep looking right) |
> | m and everything after it is too big | r = m |
| loop ends | l == r = first index with nums[i] > target | answer is l - 1 |
Mirror of the left border: a match is treated like "too small". Because l always lands one past the last match, the answer is l - 1, and l == 0 means nothing matched.
| Left border | Right border | |
|---|---|---|
left of l is | < target | <= target |
r onward is | >= target | > target |
| on a match | r = m | l = m + 1 |
| return | l | l - 1 |
| Python equivalent | bisect_left | bisect_right - 1 |
def bsRightBorder(nums, target):
if not nums:
return -1
left = 0
right = len(nums)
while left < right: # [left, right), terminating condition: left == right
mid = (left + right) // 2
if nums[mid] == target: # [mid + 1, right)
left = mid + 1
elif nums[mid] < target: # [mid + 1, right)
left = mid + 1
elif nums[mid] > target: # [left, mid)
right = mid
# nums[left-1] may be the target
if left == 0 or nums[left-1] != target:
return -1
return left - 1
Example Solutionsβ
Search In Rotated Sorted Arrayβ
This leetcode question will test your true understanding of binary search.
Solution:β
def search(self, nums):
l = 0
r = len(nums)
while l < r: # [l, r), terminating condition: l == r
mid = (l + r) // 2
if nums[mid] == target:
return mid
# target and mid on same side
if (nums[mid] < nums[0]) == (target < nums[0]):
# perform binary search
if nums[mid] < target: # [mid + 1, r)
l = mid + 1
elif nums[mid] > target: # [l, mid)
r = mid
# target on right side, search right
elif (target < nums[0]): # [mid + 1, r)
l = mid + 1
# target on left side, search left
else: # [l, mid)
r = mid
# Not found
return -1
Debugger Breakpointsβ
A CodeSignal single-function question. Given codeLength (the last line number), a sorted list of
unique breakpoints, and a list of actions, return the line the debugger ends on. It starts on
line 1. "next" moves forward one line; "continue" runs forward until it hits the next
breakpoint strictly after the current line. Both are guaranteed to be legal when performed.
"continue" is just "first breakpoint greater than line". The bound the question allows,
O(codeLength + b * a), is loose enough that a plain scan of the breakpoint list per action passes:
def solution(codeLength, breakpoints, actions):
current = 1
for action in actions:
if action == "next":
current += 1
else: # "continue"
# smallest breakpoint strictly greater than current
for bp in breakpoints:
if bp > current:
current = bp
break
return current
That is O(a * b). Write it first in an interview, then offer the improvement below.
Solution: binary searchβ
The list is sorted, so the inner scan is the right border search from above.
The comparison is <=, not <, so a debugger already sitting on a breakpoint moves to the next
one instead of staying put. codeLength never enters the logic; the guarantees mean you never run
off either end of the list.
def firstAfter(breakpoints, line):
left, right = 0, len(breakpoints)
while left < right: # [left, right)
mid = (left + right) // 2
if breakpoints[mid] <= line: # too early, search right
left = mid + 1
else: # candidate, but a smaller one may exist
right = mid
# guaranteed by the question to be in range
return breakpoints[left]
def solution(codeLength, breakpoints, actions):
line = 1
for a in actions:
if a == "next":
line += 1
else: # "continue"
line = firstAfter(breakpoints, line)
return line
assert solution(55, [2, 5, 21, 44], ["next", "next", "continue", "next", "next"]) == 7
assert solution(10, [4, 10], ["continue", "continue"]) == 10
Time Complexity: O(a log b) for a actions and b breakpoints β well inside the allowed
O(codeLength + b * a).
Space Complexity: O(1).