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
3Sum Smaller: Count Triplets with Sum < TargetInput Array:-2013Target: 2Find triplets where sum < 2:[-2, 0, 1] → sum = -1 < 2 ✓[-2, 0, 3] → sum = 1 < 2 ✓[-2, 1, 3] → sum = 2 ≥ 2 ✗Result: 2
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
Asked in
Google 25 Amazon 20 Facebook 15 Microsoft 18
28.5K 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