Mid
Detailed answer
Two Pointers
DSA & Coding Interviews
How do you solve 3Sum?
Short answer: Sort the array. Fix one number, then use two pointers on the remainder to find pairs that sum to −fixed. Skip duplicates carefully to return unique triplets. Overall O(n²).
Interview approach
- Sort ascending.
- For i from 0..n-3, skip duplicate nums[i].
- Left = i+1, right = n-1; move based on sum vs 0.
- When sum == 0, record triplet and skip duplicate left/right.
Complexity
Time O(n²), Space O(1) extra besides output (sorting may use O(log n)).
Edge cases to mention
- Fewer than 3 elements
- All zeros
- Many duplicates
Common follow-ups
- 4Sum
- 3Sum Closest
Mistakes to avoid
- Forgetting to skip duplicates → wrong unique set
- Using the same index twice
Sorting + two pointers is the pattern interviewers expect after Two Sum.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png