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.py — 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.py — 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.py — All Negative Numbers
$ Input: nums = [-5, -3, -2, -1], target = -5
Output: 2
💡 Note: Valid triplets are: (-5, -3, -2) with sum -10 < -5, and (-5, -3, -1) with sum -9 < -5. Count = 2.

Visualization

Tap to expand
🎯 Team Formation Under BudgetFind all 3-person teams with total cost < $2👨-$2Leader👩$0Assistant🧑$1Specialist👤$3ExpertValid Teams Found: 2Team 1: Leader + Assistant + Specialist = -$1 ✓Team 2: Leader + Assistant + Expert = $1 ✓
Understanding the Visualization
1
Sort by Cost
Arrange people by their salary costs: [-2, 0, 1, 3]
2
Fix Team Leader
Choose team leader (first person), then find pairs for remaining budget
3
Two Pointer Search
Use two pointers to efficiently find all valid team combinations
4
Count in Bulk
When we find one valid team, count all teams with same leader and assistant but different specialists
Key Takeaway
🎯 Key Insight: After sorting by cost, when we find one valid team, we can count multiple teams in bulk by leveraging the sorted order - if person X works as the third member, everyone cheaper than X also works!

Time & Space Complexity

Time Complexity
⏱️
O(n² log n)

O(n log n) for sorting plus O(n²) for nested loops, each doing O(log n) binary search

n
2n
Quadratic Growth
Space Complexity
O(1)

Only using constant extra space besides the input array

n
2n
Linear Space

Constraints

  • 1 ≤ nums.length ≤ 100
  • -100 ≤ nums[i] ≤ 100
  • -100 ≤ target ≤ 100
  • The array contains at least 3 elements
Asked in
Facebook 45 Google 38 Amazon 32 Microsoft 28 Apple 22
42.6K Views
Medium-High Frequency
~25 min Avg. Time
1.3K 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