Binary Search

intermediate40 min

Binary Search Overview

Binary search halves the search space each step on sorted data—or on any monotone predicate—so cost stays O(log n).

Binary Search Variations

Binary Search on Answer Space

  • Sorted Arrays: Finding elements in sorted arrays
  • Monotonic Functions: Finding values where function equals target
  • Optimization Problems: Finding minimum/maximum value satisfying conditions
  • Range Queries: Finding elements in specific ranges
  • Time Complexity: When you need O(log n) instead of O(n)

Common Mistakes

  • Integer Overflow: Use left + (right - left) / 2 instead of (left + right) / 2
  • Infinite Loops: Ensure left and right are updated correctly
  • Edge Cases: Handle empty arrays, single elements, duplicates
  • Return Value: Decide whether to return index or value