Module 3: Binary Search·Tutorial 6 of 23 (Step 3.1)
All Tutorials·DSA Roadmap·5 Problems · ~14 hrs

3.1 Binary Search (1D, 2D & Answer Space)

Understand what Binary Search is, why cutting a search space in half turns 1 billion steps into 30, and master Exact, Rotated, and Answer-Space Binary Search.

01 Read the story: What & Why
02 Follow the drawing: Visual stepper
03 Practice code: 4 languages + problems

1. What Is Binary Search?

Binary Search is a divide-and-conquer search algorithm that finds a target inside a sorted (or monotonic) collection by repeatedly checking the middle element (mid) and throwing away the entire half where the target cannot possibly be.


2. Why Do We Need Binary Search & How Does It Work?

The Pain of Linear Search (O(N)) vs. Halving (O(log N))

Suppose you have a sorted array of 1,000,000,000 (1 billion) items:

  • Linear Search (for loop): Checks items one by one from index 0. Worst case: 1,000,000,000 steps.
  • Binary Search: Checks the middle (500,000,000). With one comparison (< or >), it eliminates 500 million items! After 30 halvings (2^30 > 10^9), only 1 item is left. Worst case: 30 steps (O(log N))!
Visual: Standard Binary Search — Compare mid and Throw Away Half
25812162338✗ Discarded (< 12)mid = 12✓ Search Right (target = 23): L = mid + 11,000,000,000 items → 30 steps max (O(log N) time, O(1) space)

The 3 Core Binary Search Scenarios

  1. Standard & Boundary Search: Finding an exact number (while left <= right) or finding the first index where nums[i] >= target (while left < right).
Binary Search StyleLoop ConditionWhen nums[mid] Matches / WorksBest Used For
Exact Matchwhile left <= right:return mid immediatelyFinding a specific target value when all elements are distinct
Lower Bound (first >= target)while left < right:right = mid (keep mid and look left!)Finding the first occurrence of a duplicate or minimum feasible speed/capacity
Upper Bound (first > target)while left < right:right = mid when nums[mid] > targetCounting how many elements are <= target
  1. Rotated Sorted Arrays: When [0, 1, 2, 4, 5, 6, 7] is rotated into [4, 5, 6, 7, 0, 1, 2], at least one half ([left..mid] or [mid..right]) is still strictly sorted. Check which half is sorted, test if target lies inside that half's endpoints, and narrow the range!
Visual: Rotated Sorted Array [4, 5, 6, 7, 0, 1, 2] — Two Rising Slopes
4 (L)567 (mid)012 (R)At least ONE half ([L..mid] or [mid..R]) is always strictly sorted!
  1. Binary Search on Answer Space (Koko Eating Bananas): Even when there is no sorted array given, if a question asks "What is the minimum speed/capacity X needed to finish a task?", notice that can_finish(X) is monotonic: if speed X is too slow (False), every slower speed is also False; once speed X works (True), every faster speed also works (True)!
Visual: Monotonic Answer Space — Finding the First "True" Boundary
FFFT ★TTTisValid(mid) == True? Keep mid (R = mid) | False? Must go higher (L = mid + 1)

Step Through the Visual Drawing: Halving the Search Space

Click Next below to trace how Binary Search locates 23 by discarding half the array on every comparison:

The Hand-Drawn Step-by-Step Walkthrough
Step 1 / 2

Interactive Step-by-Step Trace: Binary Search Halving

Find target = 23 in sorted [2, 5, 8, 12, 16, 23, 38] by cutting the array in half:

Step 1: Check Middle Index 3 (value = 12)
idx 02L
idx 15
idx 28
idx 312Mid
idx 416
idx 523
idx 638R
mid = (0 + 6) // 2 = 3 -> nums[3] = 12 < 23 -> Discard indices 0..3!

12 is smaller than 23. Since the array is sorted, everything left of 12 is also too small!

✎ Remember this: One comparison eliminates 50% of the remaining candidates.

3. Basic Operations & Walkthroughs (All 4 Languages)

# 1. Standard Exact Match Binary Search -> O(log N)
def binary_search(nums: list[int], target: int) -> int:
  left, right = 0, len(nums) - 1
  while left <= right:
      mid = left + (right - left) // 2
      if nums[mid] == target:
          return mid
      elif nums[mid] < target:
          left = mid + 1
      else:
          right = mid - 1
  return -1

# 2. First True / Lower Bound Template -> O(log N)
def first_feasible(min_ans: int, max_ans: int, can_finish) -> int:
  left, right = min_ans, max_ans
  while left < right:
      mid = left + (right - left) // 2
      if can_finish(mid):
          right = mid      # mid works! Keep it and try smaller
      else:
          left = mid + 1   # mid failed! Must go higher
  return left

4. Core Interview Patterns & Common Traps

Pattern: Binary Search on Answer Space (Minimum Feasible Speed / Capacity)

Use whenever the problem asks for the minimum X (or maximum X) such that a condition can_finish(X) is True, and can_finish(X) flips monotonically from False to True.

left, right = min_possible, max_possible
while left < right:
  mid = left + (right - left) // 2
  if can_finish(mid):
      right = mid      # mid works! Keep mid and try smaller
  else:
      left = mid + 1   # mid is too small! Must go higher
return left
Operation / PatternTimeSpaceNotes
1D Binary Search (Exact / Lower Bound)O(log N)O(1)Halves search range each step
2D Sorted Matrix SearchO(log(R * C))O(1)Treat as 1D array of size R*C: row = mid // C, col = mid % C
Binary Search on Answer SpaceO(N log M)O(1)M = max_ans - min_ans; O(N) per feasibility check

5. Practice On Your Own (Curated Submodule Problems)

0 / 5 Solved
StatusProblemDifficultyComplexityHint?Links & Notes
Binary Search
Standard & Boundary Binary Search
Easy
T: O(log N)
S: O(1)
Solve
Search a 2D Matrix
Standard & Boundary Binary Search
Medium
T: O(log(R * C))
S: O(1)
Solve
Search in Rotated Sorted Array
Rotated & Peak Array Search
Medium
T: O(log N)
S: O(1)
Solve
Find Minimum in Rotated Sorted Array
Rotated & Peak Array Search
Medium
T: O(log N)
S: O(1)
Solve
Koko Eating Bananas
Binary Search on Answer Space
Medium
T: O(N log M)
S: O(1)
Solve