Explanation
3Sum is a Medium interview problem tagged [Array, Two Pointers]. The winning approach is typically **Two Pointers**.
#15
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.
Notice that the solution set must not contain duplicate triplets.
Example 1
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
The distinct triplets that sum to 0.
Example 2
Input: nums = [0,1,1]
Output: []
The only possible triplet does not sum to 0.
Example 3
Input: nums = [0,0,0]
Output: [[0,0,0]]
The only possible triplet sums to 0.
3Sum is a Medium interview problem tagged [Array, Two Pointers]. The winning approach is typically **Two Pointers**.
Each pointer only moves forward/backward once, guaranteeing O(n) after any required sort.
Place two indices and move them based on a comparison or invariant (sorted order, palindrome symmetry, partition).
Curated solution in C#, Python, Java, JavaScript, and C++ — switch languages with the tabs.
Time: O(n log n) or O(n)
Space: O(n)
Before coding, restate the problem, name the pattern (Two Pointers), and write the invariant or DP state in one sentence.
Got it?
Mark #15 3Sum as understood when the pattern clicks.