3Sum
Sort the array, then run Two Sum II once for every element. That's the entire algorithm, and it takes brute force from O(n³) down to O(n²). What actually costs people points is the duplicate handling. Skip too eagerly and you drop valid triplets; skip too little and the same triplet lands in your output twice. That balance is the only genuinely hard part of this problem.
What's inside
- 1 problem, worked step by step
- 2 diagrams
- about 30 min
Premium lessonData Structures & Algorithms
Keep going with Premium.
All 78 lessons and 103 worked problems in this course, plus what 100 companies ask, pulled from 20,000+ candidate reports.
100 companies. Checked every month.
Unlock the full course$49 a year · less than $1 a week · Cancel anytime