Binary Search
Efficiently find an element in a sorted array by repeatedly dividing the search interval in half.
What is Binary Search?
Binary Search is a foundational algorithm for finding a target value within a sorted array. It works by repeatedly comparing the target to the middle element of the array.
The Motivation: Dictionary Search
Imagine finding a word in a dictionary. You don't read every word from the start (Linear Search). Instead, you open the book to the middle. If the target word is alphabetically after the middle, you discard the first half and search the second half. You repeat this until you find the word.
Attempt 1: Linear Search (Brute Force)
The simplest way is to check every element from left to right.
function search(nums: number[], target: number): number {
for (let i = 0; i < nums.length; i++) {
if (nums[i] === target) return i;
}
return -1;
}
Why it fails
- Time Complexity: O(n). If the array helps 1 billion elements, you might make 1 billion comparisons.
- Inefficient: It ignores the fact that the array is sorted.
The Intuition: Divide and Conquer
Since the array is sorted, we can rule out half of the elements in one step.
- Pick the middle element.
- If
middle === target, we are done. - If
middle < target, the target must be in the right half (all elements to left are simpler). - If
middle > target, the target must be in the left half. - Repeat on the smaller subarray.
Interactive Walkthrough
Initializing...
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.- What is Binary Search?
- The Motivation: Dictionary Search
- Attempt 1: Linear Search (Brute Force)
- The Intuition: Divide and Conquer
- Interactive Walkthrough
- Dry Run Table
- The Solution Template
- Edge Cases
- Time & Space Analysis
- Summary
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
