Interactive Lab · DSA & Algorithms

Find one number among a thousand in ten guesses, the trick every interview asks about

Binary search is the first real algorithm in every placement prep: given a sorted array, don't scan it, halve it. Look at the middle; if your target is smaller, throw away the right half; if larger, throw away the left. Every comparison deletes half of what's left, so a million elements fall in about twenty steps instead of a million. It's dead simple, and the source of more off-by-one bugs than any other loop you'll write. Drag the target and scrub the steps to see exactly how lo, mid and hi close in.

🎬 Watch the 90-second explainer, then close in on a target yourself below ↓

▶ The playground, pick a target, then scrub through each comparison

The array is sorted. Shaded cells are still in play (between lo and hi); dimmed cells have been eliminated. The ◆ marks mid, the one element binary search actually looks at this step.

target find 57
step 0 of 4

🧭 Where this fits

Binary search runs inside every database index (B-trees are its disk-shaped cousin), git bisect (find the bad commit in log₂ n builds), load balancers picking timeout thresholds, and standard libraries everywhere (bisect, lower_bound). The sorted-data prerequisite you just proved is the whole reason databases keep indexes sorted.

The code that's actually running, the loop, and the two bugs it hides



  

🔮 Predict, then test

Set the target to a value that is not in the array (slide it between two elements). Predict: how many steps before binary search gives up? (For 16 elements, at most 4⌈log₂ 16⌉because it still halves the space every time, hit or miss.) Now think about linear search scanning left to right: its worst case is the last element, 16 comparisons. That gap, 4 versus 16 here, 20 versus a million at scale, is the whole reason interviewers ask. Why does the array have to be sorted for any of this to work?

The takeaway

Your new mental model of binary search