Count Pairs Whose Sum is Less than Target - Problem

You are given a 0-indexed integer array nums of length n and an integer target. Your task is to count all valid pairs of indices where the sum of their corresponding values is strictly less than the target.

A valid pair (i, j) must satisfy:

  • 0 โ‰ค i < j < n (i comes before j)
  • nums[i] + nums[j] < target (sum is strictly less than target)

Return the total number of such pairs.

Example: If nums = [1, 3, 2, 4] and target = 5, the pairs (0,1), (0,2), and (2,1) have sums 4, 3, and 5 respectively. Only the first two are valid since they're less than 5.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [-1,1,2,3,1], target = 2
โ€บ Output: 3
๐Ÿ’ก Note: The valid pairs are: (-1,1) with sum 0, (-1,1) with sum 0 (second occurrence), and (-1,2) with sum 1. Note that we count index pairs, so (0,1), (0,4), and (0,2) are the three valid pairs.
example_2.py โ€” No Valid Pairs
$ Input: nums = [-6,2,5,-2,-7,-1,3], target = -2
โ€บ Output: 10
๐Ÿ’ก Note: Multiple pairs have sums less than -2. After systematic checking: (-6,-7), (-6,-2), (-6,-1), (-7,2), (-7,5), (-7,-2), (-7,-1), (-7,3), (-2,-1), and others form valid combinations.
example_3.py โ€” Edge Case
$ Input: nums = [1,1], target = 3
โ€บ Output: 1
๐Ÿ’ก Note: Only one pair (0,1) exists with sum 1+1=2, which is less than target 3, so the answer is 1.

Constraints

  • 1 โ‰ค nums.length โ‰ค 50
  • -50 โ‰ค nums[i], target โ‰ค 50
  • Array contains at least 2 elements

Visualization

Tap to expand
Team Formation: Two-Pointer Strategy-1COACH 11123COACH 2Skill Sum CheckThe Smart Counting InsightIf weakest + strongest < target, then weakest can team with EVERYONE in between!Count = (right_position - left_position) valid teams formed instantlyThis eliminates the need to check each pairing individuallyValid PairSum < TargetCount FastMultiple PairsMove SmartNext PositionResult: O(n log n) time - much faster than checking all pairs!
Understanding the Visualization
1
Sort by Skill
Arrange all players from weakest to strongest skill level
2
Two Coach Strategy
Position one coach at weakest player, another at strongest
3
Smart Counting
When sum is valid, count all possible teams the weakest player can form
4
Efficient Movement
Move coaches strategically to avoid rechecking combinations
Key Takeaway
๐ŸŽฏ Key Insight: Sorting enables us to count multiple valid pairs at once rather than checking each pair individually, dramatically improving efficiency from O(nยฒ) to O(n log n).
Asked in
Amazon 35 Google 28 Meta 22 Microsoft 18
28.4K Views
Medium Frequency
~12 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