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
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).
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code