2917. Count Pairs Whose Sum is Less than Target
My accepted JavaScript solution to LeetCode problem 2917, Count Pairs Whose Sum is Less than Target, running in 3ms.
- Difficulty: Easy
- JavaScript
- Runtime 3ms
- Memory 56.7MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
JavaScript
Accepted on LeetCode — runtime 3ms, memory 56.7MB, accepted 2025-12-29.
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var countPairs = function(nums, target) {
nums.sort((a, b) => a - b);
let count = 0, left = 0, right = nums.length - 1;
while (left < right) {
if (nums[left] + nums[right] < target) {
count += right - left;
left++;
} else {
right--;
}
}
return count;
}