Count Pairs Whose Sum is Less than Target

Count pairs (i, j) with i < j and nums[i] + nums[j] < target — sort then converging two pointers.

Easy
Time O(n log n) Space O(1)
LeetCode
3 min read
binary-search two-pointers sorting

Problem#

Count pairs (i, j) with i < j and nums[i] + nums[j] < target.

Examples#

  • nums = [-1,1,2,3,1], target = 23

Constraints#

  • 1 <= n <= 50.

Approach#

Sort. For each i, binary-search the largest j > i with nums[i] + nums[j] < target; add j - i to the count. Two-pointer converging version is equivalent and slightly cleaner.

Solution#

Count Pairs (sum < target)
class Solution {
public:
int countPairs(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int l = 0, r = nums.size() - 1, ans = 0;
while (l < r) {
if (nums[l] + nums[r] < target) { ans += r - l; ++l; }
else --r;
}
return ans;
}
};

Editorial#

After sorting, the two-pointer trick gives O(n): for each l, the largest valid r is non-increasing as l grows. The count r - l adds every pair (l, m) with l < m <= r.

Complexity#

  • Time: O(n log n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.