Count Pairs Whose Sum is Less than Target - Problem

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.

You need to count all valid pairs where the sum of two elements is strictly less than the target value.

Input & Output

Example 1 — Basic Case
$ Input: nums = [-4,1,1,3], target = 2
Output: 3
💡 Note: Valid pairs: (0,1): -4+1=-3, (0,2): -4+1=-3, (0,3): -4+3=-1. All have sums < 2. Total: 3 pairs.
Example 2 — No Valid Pairs
$ Input: nums = [-1,1,2,3,1], target = 2
Output: 3
💡 Note: Valid pairs: (-1,1), (-1,1), (-1,2). Other sums are ≥ 2.
Example 3 — All Pairs Valid
$ Input: nums = [-5,-3,-2,-1], target = 0
Output: 6
💡 Note: All negative numbers, so all 6 pairs have negative sums < 0.

Constraints

  • 2 ≤ nums.length ≤ 50
  • -50 ≤ nums[i] ≤ 50
  • -50 ≤ target ≤ 50

Visualization

Tap to expand
Count Pairs Whose Sum is Less than Target INPUT nums array: -4 i=0 1 i=1 1 i=2 3 i=3 target = 2 All Valid Pairs (i,j): (0,1): -4+1=-3 (0,2): -4+1=-3 (0,3): -4+3=-1 (1,2): 1+1=2 (1,3): 1+3=4 (2,3): 1+3=4 Green: sum < 2 (valid) Red: sum >= 2 (invalid) Condition: nums[i] + nums[j] < target ALGORITHM STEPS 1 Sort Array [-4, 1, 1, 3] (Already sorted) 2 Two Pointers left=0, right=n-1 Move inward 3 Check Sum If sum < target: count += right-left left++ 4 Else right-- (reduce sum) Continue until done Iterations: L=0,R=3: -4+3=-1<2 +3 L=1,R=3: 1+3=4>=2 R-- L=1,R=2: 1+1=2>=2 R-- FINAL RESULT Output: 6 OK - 6 valid pairs found Valid Pairs Summary: 1. (0,1): -4+1 = -3 < 2 2. (0,2): -4+1 = -3 < 2 3. (0,3): -4+3 = -1 < 2 4. (1,2): 1+1 = 2 NOT 5. (1,3): 1+3 = 4 NOT 6. (2,3): 1+3 = 4 NOT 3 from L=0 + 3 brute = 6 Key Insight: With sorted array and two pointers: if nums[left] + nums[right] < target, then ALL pairs (left, left+1), (left, left+2), ..., (left, right) are valid. This gives us (right - left) pairs at once! Time Complexity: O(n log n) for sorting + O(n) for two pointers = O(n log n) overall TutorialsPoint - Count Pairs Whose Sum is Less than Target | Two Pointer Approach
Asked in
Google 15 Amazon 12 Microsoft 8
25.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen