This is how I usually approach the binary search implementation. First, I define aninvariantfor the pointers. For example, in some cases, I want to ensure that the left pointer (l) always points to a position that is strictly less than the answer, while the right pointer (r) should alwa...
Let's try to speed up the algorithm. We initialize the response area, i.e. such an interval [l, r] on which the answer is (i ∈ [l, r]). In at the very beginning l = 1, r = n. Then we have 2 cases: • l = r. And if a[l] = x, then we have found the answer...
Binary search on the answer¶Such situation often occurs when we're asked to compute some value, but we're only capable of checking whether this value is at least i . For example, you're given an array a1,…,an and you're asked to find the maximum floored ...