Skip to main content

LeetCode Patterns

Modified Binary Search Pattern

Modified Binary Search adapts the classic logarithmic search to inputs that are sorted-then-rotated, infinite, two-dimensional, or organized around an answer-space rather than a literal value. It compresses an O(n) scan into O(log n) by halving the search range on every iteration, using O(1) space.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Complexity

Time
O(log n)
Space
O(1)

When to use Modified Binary Search

  • The input is sorted but rotated, or has a single "pivot" or peak you need to locate.
  • The input is sorted but you don't know its length up front (infinite array problems).
  • The input is a 2D matrix whose rows and/or columns are sorted.
  • You are searching over an answer-space ("smallest k that satisfies P") and P is monotonic in k.
  • You need to find the leftmost or rightmost occurrence of a value in a sorted array with duplicates.

Template

function binarySearch(nums, target) {
  let left = 0;
  let right = nums.length - 1;
  while (left <= right) {
    const mid = left + Math.floor((right - left) / 2);
    if (nums[mid] === target) {
      return mid;
    } else if (nums[mid] < target) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }
  return -1;
}

Example LeetCode problems

#ProblemDifficultyFrequency
704Binary Searcheasyfoundational
33Search in Rotated Sorted Arraymediumcompany favorite
153Find Minimum in Rotated Sorted Arraymediumfrequently asked
34Find First and Last Position of Element in Sorted Arraymediumfrequently asked
74Search a 2D Matrixmediumclassic
162Find Peak Elementmediumfrequently asked
875Koko Eating Bananasmediumcompany favorite
1011Capacity To Ship Packages Within D Daysmediumcompany favorite
4Median of Two Sorted Arrayshardcompany favorite

Common mistakes

  • Computing `mid = (left + right) / 2` and overflowing on 32-bit integers; use `left + (right - left) / 2` instead.
  • Using `left < right` vs `left <= right` without matching the rest of the loop — the two styles produce subtly different post-conditions.
  • On rotated arrays, deciding which half is sorted using the wrong comparison and recursing into the unsorted half.
  • Forgetting to update `left` or `right` to `mid` (instead of `mid + 1` / `mid - 1`) in answer-space searches, causing infinite loops.
  • Returning the index instead of the value (or vice versa) on the recursive-base case.

Frequently asked questions

What is the difference between binary search on values and binary search on an answer space?

Value search looks up an exact element in a sorted array. Answer-space search picks a candidate answer k, evaluates a monotonic predicate P(k), and narrows the range based on whether P held. Examples: minimum eating speed, minimum ship capacity, maximum splitting size.

How do I find the leftmost vs rightmost occurrence of a value?

Run binary search but never return on equality. For leftmost, move `right` to `mid - 1` when `nums[mid] >= target` and remember the candidate. For rightmost, move `left` to `mid + 1` when `nums[mid] <= target`.

Why is binary search relevant to a 2D matrix?

If the matrix is fully sorted (each row sorted and the first element of each row greater than the last element of the previous row), you can treat it as a flattened sorted array of length m*n. If only rows and columns are sorted, you instead start from a corner and step row/column based on comparisons.

When should I prefer binary search over linear search?

Whenever the input is sorted (or sortable as a one-time cost) and the comparison cost is cheap. Binary search wins on inputs of size 100 or more; below that the constant factors of linear scan are usually faster.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill the Modified Binary Search pattern under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →