Imagine you have a list of numbers, and someone asks you a simple question: "Can you find three numbers in this list that add up to exactly zero?" Not just one group — they want every possible group of three.
That is the Three Sum problem. Let's understand it step by step.
You are given an array (a list) of whole numbers called arr. You must find all groups of three numbers from the array that satisfy two conditions:
In code terms, you pick three positions i, j, and k. The rule i != j, i != k, and j != k simply means all three positions must be different from each other. You are not allowed to use the same slot twice. Then the values at those positions must satisfy:
arr[i] + arr[j] + arr[k] == 0
Each valid group of three is called a triplet, written as [arr[i], arr[j], arr[k]]. You can return the triplets in any order — the order does not matter.
Take this input:
arr = [-1, 0, 1, 2, -1, -4]
The answer is:
[[-1, -1, 2], [-1, 0, 1]]
Let's check why:
-1 + -1 + 2 = 0 ✅ — the two -1 values come from two different spots in the array (position 0 and position 4), so this is allowed.-1 + 0 + 1 = 0 ✅2, -4, and something else? 2 + (-4) = -2, and there is no single number left that equals 2 to fix it up in a valid way, so no triplet there.Notice something important: the two -1 values are at different positions, so using both is perfectly fine. The "different positions" rule is about slots in the array, not about the values being different.
Here is the trickiest part. Look at this line:
> The solution set must not contain duplicate triplets.
This means the final list of answers must not repeat the same triplet twice. Two triplets count as the same if they contain the same numbers, even if those numbers were picked from different positions.
For example, with arr = [0, 0, 0]:
arr = [0, 0, 0][[0, 0, 0]]There is only one triplet in the answer, even though there are three zeros you could pick from. Because [0, 0, 0] made from any choice of positions looks exactly the same, you list it only once.
So you must be careful to avoid reporting the same combination of values more than once.
A beginner's first idea is the brute force approach: try every possible group of three positions using three nested loops, and keep the ones that sum to zero. This works, but it is slow because it checks a huge number of combinations.
A smarter and very common approach is:
The function you fill in looks like this in C++:
vector<vector<int>> threeSum(vector<int> & arr)
It takes the array and returns a list of triplets, where each triplet is itself a small list of three integers.
0.