Binary Search
Easy

Binary Search

Efficiently find an element in a sorted array by repeatedly dividing the search interval in half.
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.

  1. Pick the middle element.
  2. If middle === target, we are done.
  3. If middle < target, the target must be in the right half (all elements to left are simpler).
  4. If middle > target, the target must be in the left half.
  5. Repeat on the smaller subarray.
Interactive Walkthrough
Step 1 / 1

Initializing...

1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.
Unlock VisualizerPREMIUM FEATURE

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.

Start Your Premium Prep