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?
- A. The loop returns lo, and it is the first index with pred true, or n if none
- B. The loop returns hi − 1 because hi always stops one step past the answer
- C. If pred(mid) is true we must set lo = mid, or the loop can skip the answer
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Parcels with weights [4, 9, 2, 7, 5, 8, 3, 6] must be shipped in this order, and a ship carries a contiguous block each day. What is the…
- What is the largest integer k such that 1 + 2 + ... + k is at most 2023?
- A train makes three legs of lengths 1, 3 and 2 km. Each leg except the last must be finished in whole hours (a partial hour is rounded…
- How many indices i in [1, 7, 3, 6, 5, 6] have the sum of elements strictly left of i equal to the sum of elements strictly right of i?
- How many contiguous subarrays of [1, -1, 2, -2, 3, -3, 1] sum to exactly 1?
- How many contiguous subarrays of [2, 5, 1, 4, 3] have their maximum equal to the first or the last element of the subarray?