Leetcode 2824. Count Pairs Whose Sum is Less than Target
Given a 0-indexed integer array nums
of length n
and an integer target
, return the number of pairs (i, j)
where 0 <= i < j < n
and nums[i] + nums[j] < target
.
nums
and the target
?nums
contain negative numbers?nums
?To solve this problem, we need to count all pairs (i, j)
such that the sum of the elements at these indices is less than target
. Here’s the step-by-step strategy:
(i, j)
, where 0 <= i < j < n
, check if nums[i] + nums[j] < target
.nums
.target
.Given typical constraints in coding interviews, starting with the brute force solution to illustrate understanding and then optimizing if required is a good approach.
Here’s the brute force solution to count the pairs:
#include <vector>
using namespace std;
class Solution {
public:
int countPairsLessThanTarget(vector<int>& nums, int target) {
int count = 0;
int n = nums.size();
for (int i = 0; i < n - 1; ++i) {
for (int j = i + 1; j < n; ++j) {
if (nums[i] + nums[j] < target) {
++count;
}
}
}
return count;
}
};
n
.Would you need the optimized solution with two pointers as well?
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?