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 - Optimal Solution INPUT Array: nums -2 i=0 0 i=1 1 i=2 3 i=3 target = 2 Find triplets where: nums[i]+nums[j]+nums[k] < target Constraint: 0 <= i < j < k < n n = 4 ALGORITHM STEPS 1 Sort Array [-2, 0, 1, 3] (already sorted) 2 Fix First Element Iterate i from 0 to n-3 3 Two Pointers left = i+1, right = n-1 Move based on sum 4 Count Valid Triplets If sum < target: count += right - left Example: i=0, nums[i]=-2 0 L 1 3 R -2+0+3=1 1 < 2 [OK] FINAL RESULT Valid Triplets Found: Triplet 1: (-2, 0, 1) -2 + 0 + 1 = -1 < 2 Triplet 2: (-2, 0, 3) -2 + 0 + 3 = 1 < 2 OUTPUT 2 Total count of triplets with sum < target Time: O(n^2) | Space: O(1) Key Insight: After sorting, when sum < target with two pointers L and R, ALL elements between L and R also form valid triplets. This allows counting (R - L) triplets at once instead of checking each individually, reducing O(n^3) to O(n^2). TutorialsPoint - 3Sum Smaller | Two Pointer Approach
Asked in
Google 25 Amazon 20 Facebook 15 Microsoft 18
28.6K 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