High interview relevanceRoadmap: Beginner
TimeO(log n)
SpaceO(1) iterative

Why it costs this much

Each comparison halves the remaining range, so after k steps n / 2^k items remain. That reaches 1 when k equals log₂ n.

Code

import bisect
i = bisect.bisect_left(sorted_items, target)    # O(log n)
found = i < len(sorted_items) and sorted_items[i] == target
# Each step halves the range: n -> n/2 -> n/4 -> ... -> 1 takes log2(n) steps.

Python is the baseline example used across the site.

Common pitfalls

Off-by-one mistakes in lo, hi, and mid are the usual bug. The input must already be sorted, and sorting first costs O(n log n).

Operation by operation

OperationBestAverageWorstSpace
Binary searchO(1)O(log n)O(log n)O(1) iterative; O(log n) recursive

Binary search. Input is sorted and supports O(1) random access. Sorting first costs O(n log n). On a linked list the middle element costs O(n) to reach, so there is no speedup.

Keyboard shortcuts

/
Search topics
?
Show this list of shortcuts
r
Open the revision sheet
b
Save or unsave the focused card, or the topic you are reading
l
Mark the focused card, or the topic you are reading, as learned
Space Left arrow Right arrow
In the visualizer: play or pause, step back, step forward
1 to 4 Enter
In the quiz: pick an answer, then go to the next question
Escape
Close this list