LeetCode solutions

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

Read the problem on LeetCode View on GitHub

JavaScript

Accepted on LeetCode — runtime 3ms, memory 56.7MB, accepted 2025-12-29.

javascript
/**
* @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;
}

Source