3Sum
💻 Try it yourself first. Write your solution in Java, C++, Python or JavaScript and run it against hidden tests, right here.Revision notes
3Sum (online-test style)
Video: “3Sum” on LearnWithKiriti (Kodee and Mr. Tock). Arrays series, episode 17. LeetCode 15, Medium. Taught as an online coding test: three rounds, 5:00 on the clock while typing each (15 minutes), and the fast answer grows out of the slow one.
Return every triplet [a, b, c] from three different positions of nums with a + b + c == 0. Each triplet only once, in any order.
nums = [-1, 0, 1, 2, -1, -4] -> [[-1, -1, 2], [-1, 0, 1]]
nums = [2, 4, -4, -3, 6, 0, -3, -3, 4] -> [[-4, 0, 4], [-3, -3, 6]] (the video's nine cards)
| Folder | Approach | Time | Extra space |
|---|---|---|---|
Brute-EveryTriplet/ |
first, second after it, third after that; a hit is sorted and stored in a set found, so a repeat lands on the copy already there |
O(n³) | the set |
Better-HashSet/ |
Fix first; the rest is Two Sum: need = -(nums[first] + nums[second]), look it up in seen (emptied for every first), then add nums[second] |
O(n²) | O(n) |
Optimal-SortAndTwoPointers/ |
Sort; for each first squeeze left and right: too small → left up, too big → right down; skip repeated first, left and right |
O(n²) | O(1) |
Rebuild it
Fix one. Two Sum the rest. Sort, squeeze, skip the repeats.
- What do I fix? One card,
first. The rest is Two Sum with target-nums[first]. - Why a set in rounds 1 and 2? A triplet is sorted before it is stored, so the same three numbers always look the same; the set’s hash code + equals keep it once (Java
HashSetofList, Pythonsetof tuples, C++setof vectors, JavaScriptMapkeyed by the joined text). - What does sorting buy me? Two things: the squeeze, so no memory, and equal numbers side by side, so no set.
- Why the squeeze never misses: if
nums[first] + nums[left] + nums[right]is too small,nums[left]with ANY card up torightis too small, so drop left (mirror for too big). For one first on nine cards, that is at most 7 looks instead of 28 pairs. - Which three repeats do I skip?
firstequal to the one before; after a hit,leftequal to the one before andrightequal to the one after. Each is one while loop (or acontinue). - Bonus (not in the code): once
nums[first] > 0, three numbers that big can’t make zero, so you could stop early. - Imports not allowed in your test? Drop
import java.util.*;and writejava.util.beforeList,Set,HashSet,ArrayList,ArraysandCollections. - The ladder: 2Sum finds a pair, 3Sum = fix one + Two Sum, 4Sum = fix two + Two Sum.
Practise it on learnwithkiriti.com (notes, code in 4 languages, Memory Pairs level 2, a mock interview with Mr. Tock, Shelf Bot animates your own code), or next to the video in the Kodee Practice Chrome extension (link in the video description).
See the pseudocode.md in each folder. Every program was compiled, run and tested.
Brute: Every Triplet
R1 Brute: every triplet
found = empty set
for each first from 0:
for each second after first:
for each third after second:
if nums[first] + nums[second] + nums[third] == 0:
sort the three, add to found
return everything in found
Why each loop starts after the one before: no position is used twice, and each group of three positions is tried once. Why sort before storing: -1, 0, 1 and 0, 1, -1 are the same triplet; sorted, they look the same, so the set keeps one. Check on the nine cards [2, 4, -4, -3, 6, 0, -3, -3, 4]: 84 tries, 5 hits, 2 kept ([-4, 0, 4] and [-3, -3, 6]); the other 3 hits are repeats the set throws away. Cost: n × (n − 1) × (n − 2) ÷ 6 tries. 9 cards = 84. O(n³) time, the set is extra space.
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Set<List<Integer>> found = new HashSet<>();
for (int first = 0; first < nums.length; first++) {
for (int second = first + 1; second < nums.length; second++) {
for (int third = second + 1; third < nums.length; third++) {
if (nums[first] + nums[second] + nums[third] == 0) {
// sorted, so the same three numbers always look the same
List<Integer> triplet = Arrays.asList(nums[first], nums[second], nums[third]);
Collections.sort(triplet);
found.add(triplet);
}
}
}
}
return new ArrayList<>(found);
}
}class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
set<vector<int>> found;
for (int first = 0; first < nums.size(); first++) {
for (int second = first + 1; second < nums.size(); second++) {
for (int third = second + 1; third < nums.size(); third++) {
if (nums[first] + nums[second] + nums[third] == 0) {
// sorted, so the same three numbers always look the same
vector<int> triplet = {nums[first], nums[second], nums[third]};
sort(triplet.begin(), triplet.end());
found.insert(triplet);
}
}
}
}
return vector<vector<int>>(found.begin(), found.end());
}
};def threeSum(nums):
found = set()
for first in range(len(nums)):
for second in range(first + 1, len(nums)):
for third in range(second + 1, len(nums)):
if nums[first] + nums[second] + nums[third] == 0:
# sorted, so the same three numbers always look the same
triplet = tuple(sorted((nums[first], nums[second], nums[third])))
found.add(triplet)
return [list(triplet) for triplet in found]function threeSum(nums) {
const found = new Map();
for (let first = 0; first < nums.length; first++) {
for (let second = first + 1; second < nums.length; second++) {
for (let third = second + 1; third < nums.length; third++) {
if (nums[first] + nums[second] + nums[third] === 0) {
// sorted, so the same three numbers always look the same
const triplet = [nums[first], nums[second], nums[third]].sort((a, b) => a - b);
found.set(triplet.join(','), triplet);
}
}
}
}
return [...found.values()];
}Better: Hash Set
R2 Better: fix first, then Two Sum with a hash set
found = empty set
for each first from 0:
seen = empty set
for each second after first:
need = -(nums[first] + nums[second])
if need in seen: sort the three, add to found
add nums[second] to seen
return everything in found
Derivation: in one row of the brute, first and second are fixed and third walks the whole rest of the row looking for ONE number: minus first, minus second. That is Two Sum with target minus first, so remember the cards second has passed.
Two rules: seen empties when first moves (earlier cards already had their turn as first), and check BEFORE you add (a card can’t pair with itself).
What a hash set is: an array of slots. A formula turns a number into a hash code, which picks one slot; to check a number, the same formula jumps straight to that slot. Two numbers in one slot is a collision: the slot keeps both and equals tells them apart. O(1) on average.
Check on the nine cards: 36 checks, 5 hits, 2 kept; found still throws the repeats away.
Complexity: O(n²) time, O(n) extra space for seen (plus the set).
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Set<List<Integer>> found = new HashSet<>();
for (int first = 0; first < nums.length; first++) {
// Two Sum on the numbers after first, with target -nums[first]
Set<Integer> seen = new HashSet<>();
for (int second = first + 1; second < nums.length; second++) {
int need = -(nums[first] + nums[second]);
if (seen.contains(need)) {
List<Integer> triplet = Arrays.asList(nums[first], nums[second], need);
Collections.sort(triplet);
found.add(triplet);
}
seen.add(nums[second]);
}
}
return new ArrayList<>(found);
}
}class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
set<vector<int>> found;
for (int first = 0; first < nums.size(); first++) {
// Two Sum on the numbers after first, with target -nums[first]
unordered_set<int> seen;
for (int second = first + 1; second < nums.size(); second++) {
int need = -(nums[first] + nums[second]);
if (seen.count(need)) {
vector<int> triplet = {nums[first], nums[second], need};
sort(triplet.begin(), triplet.end());
found.insert(triplet);
}
seen.insert(nums[second]);
}
}
return vector<vector<int>>(found.begin(), found.end());
}
};def threeSum(nums):
found = set()
for first in range(len(nums)):
# Two Sum on the numbers after first, with target -nums[first]
seen = set()
for second in range(first + 1, len(nums)):
need = -(nums[first] + nums[second])
if need in seen:
triplet = tuple(sorted((nums[first], nums[second], need)))
found.add(triplet)
seen.add(nums[second])
return [list(triplet) for triplet in found]function threeSum(nums) {
const found = new Map();
for (let first = 0; first < nums.length; first++) {
// Two Sum on the numbers after first, with target -nums[first]
const seen = new Set();
for (let second = first + 1; second < nums.length; second++) {
const need = -(nums[first] + nums[second]);
if (seen.has(need)) {
const triplet = [nums[first], nums[second], need].sort((a, b) => a - b);
found.set(triplet.join(','), triplet);
}
seen.add(nums[second]);
}
}
return [...found.values()];
}Optimal: Sort And Two Pointers
R3 Optimal: sort, squeeze, skip the repeats
sort nums
triplets = empty list
for each first, up to the third from the end:
same as the one before? skip
left = first + 1; right = last
while left < right:
sum = nums[first] + nums[left] + nums[right]
too small: left up; too big: right down
zero: add the triplet, left up, right down
skip equal numbers: left up, right down
return triplets
Derivation: the repeats came from equal numbers far apart (three -3s, two 4s). Sort the row and they sit side by side, so a repeat is “same as my neighbour? skip”. A sorted row also gives Two Sum II’s squeeze, so seen goes too.
Why the squeeze never misses: too small means left with every card up to right is too small, so left is useless: drop it. Too big works the other way for right.
Why it is faster: for one first on nine cards, the brute tries 28 pairs of the cards after it; the squeeze drops one card per look, at most 7. Sorting costs n log n once, and we return numbers, not positions, so the new order is fine.
Dry run on the sorted cards [-4, -3, -3, -3, 0, 2, 4, 4, 6]: first -4 squeezes to [-4, 0, 4], then right lands on the other 4: skip. First -3 finds [-3, -3, 6], then left lands on another -3: skip. The next two -3s as first: skip. First 0, 2 and 4 find nothing. Two triplets, 15 looks, no memory, no set.
Bonus (not in the code): once nums[first] > 0, stop early.
Complexity: O(n²) time, O(1) extra space apart from the answer.
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> triplets = new ArrayList<>();
for (int first = 0; first < nums.length - 2; first++) {
// same first number as last time: its triplets are already found
if (first > 0 && nums[first] == nums[first - 1]) {
continue;
}
int left = first + 1;
int right = nums.length - 1;
while (left < right) {
int sum = nums[first] + nums[left] + nums[right];
if (sum < 0) {
left++;
} else if (sum > 0) {
right--;
} else {
triplets.add(Arrays.asList(nums[first], nums[left], nums[right]));
left++;
right--;
// skip repeats so the same triplet is not added twice
while (left < right && nums[left] == nums[left - 1]) {
left++;
}
while (left < right && nums[right] == nums[right + 1]) {
right--;
}
}
}
}
return triplets;
}
}class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> triplets;
for (int first = 0; first + 2 < nums.size(); first++) {
// same first number as last time: its triplets are already found
if (first > 0 && nums[first] == nums[first - 1]) {
continue;
}
int left = first + 1;
int right = nums.size() - 1;
while (left < right) {
int sum = nums[first] + nums[left] + nums[right];
if (sum < 0) {
left++;
} else if (sum > 0) {
right--;
} else {
triplets.push_back({nums[first], nums[left], nums[right]});
left++;
right--;
// skip repeats so the same triplet is not added twice
while (left < right && nums[left] == nums[left - 1]) {
left++;
}
while (left < right && nums[right] == nums[right + 1]) {
right--;
}
}
}
}
return triplets;
}
};def threeSum(nums):
nums.sort()
triplets = []
for first in range(len(nums) - 2):
# same first number as last time: its triplets are already found
if first > 0 and nums[first] == nums[first - 1]:
continue
left = first + 1
right = len(nums) - 1
while left < right:
sum = nums[first] + nums[left] + nums[right]
if sum < 0:
left += 1
elif sum > 0:
right -= 1
else:
triplets.append([nums[first], nums[left], nums[right]])
left += 1
right -= 1
# skip repeats so the same triplet is not added twice
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
return tripletsfunction threeSum(nums) {
nums.sort((a, b) => a - b);
const triplets = [];
for (let first = 0; first < nums.length - 2; first++) {
// same first number as last time: its triplets are already found
if (first > 0 && nums[first] === nums[first - 1]) {
continue;
}
let left = first + 1;
let right = nums.length - 1;
while (left < right) {
const sum = nums[first] + nums[left] + nums[right];
if (sum < 0) {
left++;
} else if (sum > 0) {
right--;
} else {
triplets.push([nums[first], nums[left], nums[right]]);
left++;
right--;
// skip repeats so the same triplet is not added twice
while (left < right && nums[left] === nums[left - 1]) {
left++;
}
while (left < right && nums[right] === nums[right + 1]) {
right--;
}
}
}
}
return triplets;
}