Binary Search
Software Engineer path · lesson 7 of 99Understand the power of O(log n). Visualize dividing the search space in half to find targets in sorted arrays instantly.
Up to 16 whole numbers. They're sorted before searching, because binary search only works on sorted data.
Lower bound keeps going after a match to find the leftmost one; try it on Duplicates.
Search for 23 in 10 sorted values. Each step halves the search space.
- 1lo, hi = 0, n - 1
- 2while lo <= hi:
- 3 mid = (lo + hi) // 2
- 4 if a[mid] == target: return mid
- 5 if a[mid] < target: lo = mid + 1
- 6 else: hi = mid - 1
- 7return -1 (exact) / lo (first index ≥ target)
- Comparisons
- 0 / 3
- Halvings
- 0 / 3
Tap any element in the diagram to inspect its state at this step.
Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.
Halve the search space
Order the steps of binary search on a sorted array.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
- 1Drop a step here
- 2Drop a step here
- 3Drop a step here
- 4Drop a step here
- 5Drop a step here
Test your knowledge
What precondition is REQUIRED for Binary Search?
Write the code
Search Insert Position
function searchInsert(nums, target) {
// Your code here
}The short version
Think of looking up a word in a dictionary. You open to the middle. If your word is after the page you see, you ignore the first half completely. You keep splitting the remaining pages in half until you find it.
In more depth
Divide and Conquer
Binary Search is the most efficient way to search a Sorted array.
This eliminates half the search space in every step, resulting in O(log n) complexity.
Precondition: The data MUST be sorted.
When to reach for this
- Search in a **Sorted** array
- Find a value where a condition changes (False -> True)
- Search space can be divided in half (Monotonic function)
Interview Questions
References & Further Reading
Love this visualization?
Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.
100% free • No credit card required