Skip to content

lower-bound like searches

Course: Binary search, two sum and strings - chapter 5

Firstly, what do I mean by lower-bound. It is a function that is available with the algorithm library. It returns the first index ≥ x. In these cases, you are not just searching if an element is present or not, but rather the first index that satisfies a monotonic property.

Let’s understand with an example. In the following array, find the first index that is greater than or equal to 5

int arr[] = {1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 8};

The answer should be 6.

I see these types of questions as 0-1 questions, where you can generate a 0-1 array based on the property. The property is ≥ 5.

Now elements satisfying the property get a 1, else 0.

If you think about it, as the array is increasing, initially the elements are 0, because they are less than 5. Once it becomes 5, it will always be ≥5 as the array is increasing.

So the 0-1 equivalent array will be

[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1]

💡 There are multiple ways to solve this. Below I have outlined the approach that I use and find more intuitive.

In these arrays, we need to find the first occurrence of 1. Now traditional binary search doesn’t work here as it would return true whenever it sees a one. We specifically want the first occurrence of 1. So we will tweak our binary search implementation a bit to tackle this.

  1. We will not terminate when we find the desired number (1 or 5).
  2. lo will always point to something that is not satisfying the property
  3. hi will always point to something that is satisfying the property.
  4. Or vice versa between lo and hi

If we think about the statements above, where should we end the loop?

In a state like this [0, 1], where lo points to the last 0 and hi points to the first 1.

With this in mind, let’s write the code

int lower_bound_search(vector<int> &nums, int k) {
// returns the first index, where elements are >= k
// first check for 2 extreme cases, if no element >=k or if all >=k
int n = nums.size();
if (nums[0] >= k) return 0;
else if (nums[n-1] < k) return -1; // or n whichever works
int lo = 0, hi = n-1;
while(lo < hi - 1) {
// We always end in this state, lo is one index before hi
int mid = (lo + hi)/2;
if (nums[mid] >= k) {
// all the elements on the right are definitely >= k. On the left is unknown
// so let's search on left
hi = mid; // We cannot set to mid - 1 as we are not sure if nums[mid-1] satisfies
} else {
lo = mid;
}
}
// Now hi points to the first index >= k
return hi;
}