3-Sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Examples
The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter.
The only possible triplet does not sum to 0.
The only possible triplet sums to 0.
Problem Understanding
The goal is to find all unique triplets that sum to zero. It's essentially an extension of the Two Sum problem.
Key Constraint: The solution set must not contain duplicate triplets. This implies we need to be careful about how we select numbers.
Strategy: Reduce to Two Sum
We can fix one number, say nums[i]. Then the problem becomes finding two other numbers in the rest of the array that sum to -nums[i].
Since we want to avoid duplicates and use the Two Pointer technique efficiently, our first step is to sort the array.
Algorithm:
- Sort the array.
- Iterate through the array with index
i. - For each
i, run the Two Sum (Sorted) logic on the remaining part of the array (i+1to end) withtarget = -nums[i].
Interactive Visualization
Sorted Array. Fix i = -4. Target = 4. L=-1, R=2. Sum = -4 + -1 + 2 = -3. Too small. Move L.
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.- Problem Understanding
- Strategy: Reduce to Two Sum
- Interactive Visualization
- Dry Run Table
- Edge Cases & Common Mistakes
- Solution
- Complexity Analysis
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
