Explain binary search.
Skip to solutionKEEP THE
mediumDSA
How does binary search work and what are its requirements?
1.1k views
01
Understand the problem
binary-search
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
Binary search finds a target in a sorted array in O(log n) by repeatedly comparing the middle element and discarding half the range. Requirement: random-access, sorted data. Off-by-one errors in the lo/hi/mid bounds are the classic pitfall.
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
Iterative binary search
Run Playgrounddef binary_search(arr, target):
lo, hi = 0, len(arr) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if arr[mid] == target:
return mid
if arr[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
# --- demo ---
print(binary_search([-1, 0, 3, 5, 9, 12], 9)) # 4
print(binary_search([-1, 0, 3, 5, 9, 12], 2)) # -105
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 32 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.