Practice Discrete Math

Algorithms / Binary Search Invariants

Least You Need to Know: Binary Search Invariants and Boundary Updates

Binary search works because the search interval maintains an **invariant**: the desired answer is still inside the remaining range. Each comparison must eliminate only the half that is provably impossible, and the boundary update must match the exact question being asked.

جو کم از کم جاننا ضروری ہے

اہم علامتیں

lo, hi current candidate range
mid middle index or middle candidate
invariant property that remains true after each update

مختصر حل شدہ مثال

  • Suppose you want the first index whose value is at least `x`.
  • Keep the invariant that the answer is somewhere in `[lo, hi]`.
  • If `a[mid]` is already at least `x`, keep the left half by setting `hi = mid`.
  • Otherwise eliminate `mid` and the entire left half by setting `lo = mid + 1`.

عام غلطیاں

اس قسم کے سوال کو کیسے پہچانیں

Next recommended lesson

Continue through this topic with Least You Need to Know: Bipartite Matching, Augmenting Paths, and Assignment Structure.

Least You Need to Know: Bipartite Matching, Augmenting Paths, and Assignment Structure

Related lessons

Keep going with nearby lessons in the same topic.

More ways to explore

مشق شروع کریں