Skip to content

Question:

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

Link: https://leetcode.com/problems/count-pairs-whose-sum-is-less-than-target/description/

As discussed earlier, whenever we have problems related to pairs, we can fix one element (as the right element), and search on the LHS of that element.

For each fixed element j we want to find the number of elements on the LHS that are less than target - arr[j].

Let’s assume the array is sorted. How can we find the number of elements <k in the array?

We can find the first index ≥ k (let’s say the index is idx), then the number of elements <k is idx (0 - idx-1).

So we will sort, our main array and run the algorithm. That is iterate over all elements and fix them as j. For each element identify how many elements are there on the L.H.S i.e (0, j-1)

that are < (target - arr[j]) using Binary Search.

This brings us to our next topic, lower-bound searches.

So, in the above case, it is similar to finding lower-bound of target - arr[j].

class Solution {
public:
int compute(vector<int> &nums, int k, int beg, int end) {
// Number of elements < k in range [beg, end]
if (nums[beg] >= k) return 0;
else if (nums[end] < k) return (end - beg + 1);
int lo = beg, hi = end;
while (lo < hi - 1) {
int mid = (lo + hi) / 2;
if (nums[mid] < k) lo = mid;
else hi = mid;
}
return hi;
}
int countPairs(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int ans = 0;
for(int i=1; i<nums.size(); i++) {
ans += compute(nums, target - nums[i], 0, i-1);
}
return ans;
}
};