Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Two Pointers High frequency Solution Available Practice Mode

3Sum LeetCode Solution

Tags: #Array #Two Pointers #Sorting

Approach Summary

Sort the array, fix one element, then use two pointers for the rest. Skip duplicates carefully to avoid duplicate triplets.

Practice Mode 2 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Two Pointers Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Two Pointers pattern.

Framework: Two Pointers • Interview Prep: Tested at FAANG • Explore all Two Pointers problems & invariants →

How to Recognize This Pattern

  • Find all triplets summing to zero
  • No duplicate triplets

Complexity Analysis

Time Complexity

O(n²)

Space Complexity

O(n)

Tags

Array Two Pointers Sorting

Frequently Asked Questions

What is the optimal time and space complexity for 3Sum?
The optimal solution for 3Sum achieves O(n²) runtime complexity and requires O(n) auxiliary space. Sorting takes O(n log n). The outer loop runs n times, and the two-pointer inner scan takes O(n) per element, totaling O(n²) time. Auxiliary space is O(1) or O(log n) depending on the sorting algorithm implementation, excluding space for the returned result list.
How do I identify that 3Sum requires the Two Pointers pattern?
In technical interviews, look for key problem signals: Find all triplets summing to zero; No duplicate triplets. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Two Pointers strategy.
What critical edge cases must be handled in 3Sum?
Essential edge cases to verify include: Array with fewer than 3 elements (returns []); All zeros [0, 0, 0, 0] (returns single triplet [0, 0, 0]); Multiple identical duplicate numbers where duplicate triplets must be prevented; No triplet sums to zero. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask 3Sum?
3Sum is a Medium-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Facebook, Amazon, Google, Adobe.
Buy me a coffee
Daily Practice
0/0