3Sum Smaller - Problem
3Sum Smaller is a challenging array problem that asks you to count triplets with a sum below a target threshold.
You're given an array of n integers nums and a target integer. Your task is to find the total count of index triplets (i, j, k) where:
0 ≤ i < j < k < n(distinct indices in ascending order)nums[i] + nums[j] + nums[k] < target
For example, with nums = [-2, 0, 1, 3] and target = 2, the valid triplets are (-2, 0, 1) and (-2, 0, 3), giving us a count of 2.
Note: We only count the number of valid triplets, not the triplets themselves.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [-2, 0, 1, 3], target = 2
›
Output:
2
💡 Note:
The two valid triplets are: (-2, 0, 1) with sum -1 < 2, and (-2, 0, 3) with sum 1 < 2. Total count = 2.
Example 2 — No Valid Triplets
$
Input:
nums = [3, 4, 5, 6], target = 10
›
Output:
0
💡 Note:
The smallest possible sum is 3 + 4 + 5 = 12, which is greater than target = 10. No valid triplets exist.
Example 3 — All Negative Numbers
$
Input:
nums = [-5, -3, -2, -1], target = -5
›
Output:
4
💡 Note:
All 4 triplets have sum < -5: (-5,-3,-2)=-10, (-5,-3,-1)=-9, (-5,-2,-1)=-8, (-3,-2,-1)=-6. Count = 4.
Constraints
- 1 ≤ nums.length ≤ 100
- -100 ≤ nums[i] ≤ 100
- -100 ≤ target ≤ 100
- The array contains at least 3 elements
Visualization
Tap to expand
Understanding the Visualization
1
Sort Array
Arrange elements in ascending order: [-2, 0, 1, 3]
2
Fix First Element
Choose first element (i=0), set left=i+1 and right=n-1
3
Two Pointer Search
Use two pointers to efficiently find all valid pairs
4
Count in Bulk
When sum < target, count += (right - left), then move left pointer
Key Takeaway
🎯 Key Insight: After sorting, when we find one valid triplet with sum < target, we can count multiple triplets at once! If nums[i] + nums[left] + nums[right] < target, then all elements between left and right also form valid triplets with nums[i] and nums[left].
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code