3Sum Smaller solution explained
3Sum Smaller asks how many triples of positions in an array have a sum strictly less than a target. Sort the array, fix the first value, and sweep two pointers over the rest: whenever the sum with the left and right pointer is below the target, every value between them also works with the left one, so you add the whole gap at once and move left forward. That counts all qualifying triples in O(n²) time instead of O(n³).
By Evin JohnPublished 7 min read
What the question asks
You are given a list of integers, which may repeat and may be negative, and a target. Count the ways to pick three different positions so that the three values add up to less than the target. Two triples count separately if they use different positions, even when the values are the same. If the list has fewer than three entries, the answer is zero.
| Values | Target | Count | Qualifying triples |
|---|---|---|---|
[3, -1, 0, 2] | 3 | 2 | (-1, 0, 2) = 1 and (3, -1, 0) = 2 |
[1, 4, -3, 2, 0] | 2 | 4 | (1, -3, 2), (1, -3, 0), (4, -3, 0), (-3, 2, 0) |
[-2, -2, -2, -2] | -5 | 4 | Every choice of three positions sums to -6 |
[5, 5, 5] | 15 | 0 | The only sum equals the target, which is not strictly less |
[7, -1] | 0 | 0 | Fewer than three values |
Why interviewers like it
It looks like 3Sum, and candidates who memorized 3Sum often try to skip duplicates here, which gives the wrong count. The real test is whether you notice that a sorted window lets you count many triples in a single step. Interviewers also check that you understand why sorting is safe even though the question talks about positions: the number of position triples meeting a condition on their values does not change when you reorder the array.
Brute force and a middle step
Three nested loops over i < j < k count every triple directly in O(n³). A middle step after sorting: for each pair i < j, binary search the sorted suffix for the first value that is at least target - nums[i] - nums[j]; every index between j + 1 and that position completes a valid triple. That is O(n² log n). Both make good references, and saying them out loud shows the path to the final answer.
from bisect import bisect_left
def count_smaller_brute(nums, target):
n = len(nums)
count = 0
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
if nums[i] + nums[j] + nums[k] < target:
count += 1
return count
def count_smaller_bisect(nums, target):
a = sorted(nums)
n = len(a)
count = 0
for i in range(n):
for j in range(i + 1, n):
# first index in a[j+1:] whose value would reach the target
stop = bisect_left(a, target - a[i] - a[j], j + 1, n)
count += stop - (j + 1)
return countThe O(n²) count: batch the gap
Sort the values. Fix i, then set lo = i + 1 and hi to the last index. Look at a[i] + a[lo] + a[hi]. If it is below the target, then replacing a[hi] with any value between lo and hi keeps the sum below the target, because those values are no larger. That is hi - lo valid triples that all use i and lo, so add them and move lo right. If the sum is at or above the target, a[hi] is too big to pair with a[lo] or anything after it, so move hi left. Each step moves one pointer, so each i costs linear time.
def count_smaller(nums, target):
a = sorted(nums)
count = 0
for i in range(len(a) - 2):
lo, hi = i + 1, len(a) - 1
while lo < hi:
if a[i] + a[lo] + a[hi] < target:
count += hi - lo # a[lo] works with every index lo+1..hi
lo += 1
else:
hi -= 1
return countfunction countSmaller(nums, target) {
const a = [...nums].sort((x, y) => x - y);
let count = 0;
for (let i = 0; i < a.length - 2; i++) {
let lo = i + 1;
let hi = a.length - 1;
while (lo < hi) {
if (a[i] + a[lo] + a[hi] < target) {
count += hi - lo;
lo++;
} else {
hi--;
}
}
}
return count;
}Trace the first example. Sorted, it is [-1, 0, 2, 3] with target 3. Fix -1: with 0 and 3 the sum is 2, below 3, so add 3 - 1 = 2 triples (0 with 2, and 0 with 3) and move lo to 2. Now 2 and 3 give 4, too big, move hi, and the pointers meet. Fix 0: with 2 and 3 the sum is 5, too big, and the pointers meet. Total 2.
Do not skip duplicates here
In 3Sum you skip repeated values because the output must list unique value triples. Here the output is a count of position triples, so [-2, -2, -2, -2] must count four triples, not one. Copying the duplicate-skipping lines from a 3Sum solution is the most common wrong answer to this question, and the all-equal input is the fastest way to catch it.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Triple loop | O(n³) | O(1) |
| Pairs plus binary search | O(n² log n) | O(1) after sorting |
| Sort plus two pointers with gap counting | O(n²) | O(1) after sorting |
The answer itself can be as large as n choose 3, roughly n³/6, which is why you must count in batches; listing the triples one by one could never be faster than cubic in the worst case.
Edge cases
- Fewer than three values: the loop body never runs and the count is 0.
- A sum exactly equal to the target does not count. Use
<, not<=. - All values equal, which exposes duplicate skipping.
- A very large target, where every triple counts and the answer is n choose 3.
- A very small target, where nothing counts.
- Negative values and a negative target.
Common slips
- Adding 1 instead of
hi - lowhen the sum is small, which turns the batch count into an undercount. - Moving
hiinstead ofloafter a small sum, which loses triples. - Skipping duplicate values as in 3Sum.
- Forgetting that the default JavaScript sort compares strings.
- Worrying that sorting breaks the
i < j < krule: any three positions in the sorted array correspond to exactly one set of three positions in the original.
Saying it out loud
Fictional example
- Candidate
- The count depends only on which values are picked, not their order, so I'll sort. That lets me fix the smallest value and sweep two pointers.
- Candidate
- If the sum with lo and hi is under the target, then lo paired with anything up to hi is also under, since those values are smaller. So I add hi minus lo in one go and move lo. Otherwise hi is too large for lo and everything after it, so hi moves left.
- Candidate
- Every step moves a pointer, so each fixed value costs linear time and the total is quadratic. I won't skip duplicates, because the question counts positions; four equal values give four triples.
Related problems
3Sum Closest uses the same sorted sweep to find one best sum rather than a count. Counting in batches as a window grows is also the core trick in Subarrays with K Different Integers, where each step adds the number of valid starting points. The hash-map view of pair sums is on the Two Sum page.
Rehearsing this with Natively
When you rehearse on Mac or Windows, Natively can read a counting problem like this from a screenshot and lay out an approach with code next to your own, which makes a wrong +1 instead of hi - lo easy to spot. It transcribes the session too, so afterwards you can hear whether you explained why sorting is safe. See an AI interview assistant for how practice works.
Questions people ask
How do you solve 3Sum Smaller in O(n²)?
Sort, fix the first value, and set pointers at both ends of the rest. If the sum is below the target, add hi - lo triples at once and move lo right; otherwise move hi left.
Why is sorting allowed when the question counts index triples?
The number of position triples meeting a condition on their values does not depend on the order of the array, so reordering does not change the count.
Should you skip duplicates in 3Sum Smaller?
No. The answer counts position triples, so four equal values give four triples. Skipping duplicates as in 3Sum undercounts.
Is there an approach between brute force and two pointers?
Yes. For each pair, binary search the sorted suffix for the first value that reaches the target; that is O(n² log n).
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
