3Sum
A medium Arrays problem included in Apna College, Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.
- Topic
- Arrays
- Sheets
- 3
- Core for
- 25 roles
- Platform
- LeetCode
The problem
Given an integer array, find all unique triplets [nums[i], nums[j], nums[k]] with distinct indices that sum up to zero.
Example 1
- Input
- nums = [-1,0,1,2,-1,-4]
- Output
- [[-1,-1,2],[-1,0,1]]
- Why
- The distinct index triplets [-1,-1,2] and [-1,0,1] each sum to 0 with no duplicate sets.
Example 2
- Input
- nums = [0,1,1]
- Output
- []
- Why
- No combination of three numbers sums up to zero.
Example 3
- Input
- nums = [0,0,0]
- Output
- [[0,0,0]]
- Why
- The three zeros sum to 0 and form the single unique valid triplet.
Constraints
- 3 <= nums.length <= 3000
- -10^5 <= nums[i] <= 10^5
How to think about it
Updated 2026-09-09Fixing one number turns the problem into finding two numbers in the remaining suffix that sum to -nums[i]. Sorting the array organizes duplicate values next to each other, allowing two pointers to sweep inward while skipping identical adjacent values to guarantee that every generated triplet is unique.
Approaches, worst first
Triple nested loops with set deduplication
time O(n^3) · space O(n)
Iterate through all index triplets (i, j, k) with three nested loops, verify whether their sum is 0, sort the matched triplet, and insert it into a set to weed out duplicates. Extremely slow at cubic time and consumes significant memory for set overhead.
Hash set complement lookup
time O(n^2) · space O(n)
Fix nums[i], then for the remaining elements maintain a hash set of visited values to find -nums[i] - nums[j]. Avoids the third loop, but still requires post-processing or set hashing to filter duplicate value combinations.
Sort, then two-pointer scanWrite this one
time O(n^2) · space O(1)
Sort the array ascending. Iterate i from 0 to n - 3, skipping nums[i] == nums[i - 1]. Use two pointers low = i + 1 and high = n - 1 to find pairs summing to -nums[i]. On a match, record the triplet and advance past all identical neighbor values on both ends.
Where people lose marks · 3
- Failing to skip duplicate values for the outer loop variable i, which generates duplicate triplet solutions.
- Skipping duplicates only on one pointer instead of both left and right after recording a valid triplet.
- Terminating the inner two-pointer search after the first match rather than continuing to search for other valid pairs with the same outer element.
Full solution
Sort, then fix one number and two-pointer scan the rest for the complement sum — O(n^2) time, O(1) extra space, and the sorted order makes duplicate-triplet skipping trivial on both pointers.
Python
from typing import List
def three_sum(nums: List[int]) -> List[List[int]]:
nums.sort()
n = len(nums)
result = []
for i in range(n - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue # skip duplicate anchors
if nums[i] > 0:
break # smallest remaining value is positive, no zero sum possible
low, high = i + 1, n - 1
while low < high:
total = nums[i] + nums[low] + nums[high]
if total < 0:
low += 1
elif total > 0:
high -= 1
else:
result.append([nums[i], nums[low], nums[high]])
low += 1
high -= 1
while low < high and nums[low] == nums[low - 1]:
low += 1
while low < high and nums[high] == nums[high + 1]:
high -= 1
return result
JavaScript
function threeSum(nums) {
nums = [...nums].sort((a, b) => a - b);
const n = nums.length;
const result = [];
for (let i = 0; i < n - 2; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue; // skip duplicate anchors
if (nums[i] > 0) break; // smallest remaining value is positive, no zero sum possible
let low = i + 1;
let high = n - 1;
while (low < high) {
const total = nums[i] + nums[low] + nums[high];
if (total < 0) {
low++;
} else if (total > 0) {
high--;
} else {
result.push([nums[i], nums[low], nums[high]]);
low++;
high--;
while (low < high && nums[low] === nums[low - 1]) low++;
while (low < high && nums[high] === nums[high + 1]) high--;
}
}
}
return result;
}
The theory behind it
Arrays — the ground this problem stands on. All Arrays problems
What Arrays is
An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.
When to reach for it
Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.
How the pattern works
Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.
What each operation costs
| Operation | Time |
|---|---|
| look up element by index | O(1) |
| insert or delete at the start | O(n) |
| search an unsorted collection for a value | O(n) |
What usually goes wrong with Arrays
- Reading past the final index by checking index less than or equal to length instead of strictly less than length, triggering index out of bounds exceptions.
- Modifying length or removing elements during a forward iteration loop, which causes remaining items to shift left and skip validation on the next neighbor.
- Assuming dynamic resizing is costless inside nested loops, causing repeated memory reallocation copies when appending unknown quantities of items.
Which roles need this problem
Arrays is a core topic for these 25 roles — if you're targeting one of them, this problem is early in your path, not optional.
Secondary for 3 more roles, including Database Engineer, Bioinformatics Engineer, Networking Engineer.
Track this in your role's order
Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.
Start freeMore Arrays problems
Problem set and role mapping as of .