3Sum Smaller - Problem
Given an array of n integers nums and an integer target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.
You need to count all valid triplets where the sum of three elements is strictly less than the target value.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [-2,0,1,3], target = 2
›
Output:
2
💡 Note:
Two triplets sum to less than 2: [-2,0,1] with sum -1, and [-2,0,3] with sum 1. Both are < 2.
Example 2 — No Valid Triplets
$
Input:
nums = [0], target = 0
›
Output:
0
💡 Note:
Array has only one element, cannot form any triplets (need at least 3 elements).
Example 3 — All Triplets Valid
$
Input:
nums = [-1,-1,-1], target = 0
›
Output:
1
💡 Note:
Only one possible triplet: [-1,-1,-1] with sum -3, which is less than 0.
Constraints
- 1 ≤ nums.length ≤ 3000
- -100 ≤ nums[i] ≤ 100
- -100 ≤ target ≤ 100
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [-2,0,1,3] and target 2
2
Process
Find all triplets with sum < target
3
Output
Count of valid triplets: 2
Key Takeaway
🎯 Key Insight: Sort first, then use two pointers to efficiently count all valid triplet combinations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code