Data Structures & AlgorithmsHardGATE CS · ICPC regional

A binary search for the FIRST index where a predicate becomes true uses: lo = 0, hi = n, while lo < hi: mid = (lo + hi) // 2; if pred(mid): hi = mid else: lo = mid + 1. Which statement is correct?

  1. A. The loop returns lo, and it is the first index with pred true, or n if none
  2. B. The loop returns hi − 1 because hi always stops one step past the answer
  3. C. If pred(mid) is true we must set lo = mid, or the loop can skip the answer
  4. D. The loop never terminates when n is odd because mid can equal hi forever

Correct answer: A. The loop returns lo, and it is the first index with pred true, or n if none

With the half-open range [lo, hi) and hi = n as 'not found', the invariant keeps the first true index inside [lo, hi]. Setting lo = mid when pred(mid) holds would loop forever when lo and hi are adjacent; the hi = mid branch is what keeps the true point.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic