Introduction
The 3 Sum Problem is a very popular DSA interview question and is a natural extension of the Two Sum problem. In this problem, you are asked to find three numbers in an array whose sum is equal to zero.
This question helps interviewers understand your knowledge of arrays, sorting, the two-pointer technique, and handling duplicates.
In this article, the 3 Sum problem is explained in simple words, with clear examples and easy-to-follow code.
What is the 3 Sum Problem?
You are given an array of integers. Your task is to find all unique triplets in the array such that the sum of the three numbers is zero.
Important points to remember:
The triplets must be unique
The order of numbers inside a triplet does not matter
Example
Input: [-1, 0, 1, 2, -1, -4]
Output: [[-1, -1, 2], [-1, 0, 1]]
Explanation
The two triplets whose sum is zero are:
(-1) + (-1) + 2 = 0
(-1) + 0 + 1 = 0
Brute Force Approach (Easy but Slow)
The simplest way to solve the 3 Sum problem is to use three nested loops and check all possible triplets.
How it works
Pick the first number
Pick the second number
Pick the third number
Check if their sum is zero
Drawbacks
Time Complexity becomes O(n³)
Very slow for large arrays
Because of this, brute force is not suitable for interviews.
Optimized Approach Using Sorting and Two Pointers
The most efficient and commonly used approach for 3 Sum is:
Sort the array
Fix one element
Use two pointers to find the remaining two numbers
This reduces unnecessary checks and improves performance.
Step-by-Step Explanation
Let us understand the logic clearly.
Steps:
Sort the array
Loop through the array and fix one element at a time
For the fixed element, use two pointers:
One pointer starts from the next index
Another pointer starts from the end
Check the sum of the three numbers
Move pointers based on whether the sum is less than, greater than, or equal to zero
Skip duplicate values to avoid repeated triplets
Dry Run Example
Sorted array: [-4, -1, -1, 0, 1, 2]
Fix first element = -1
| Left | Right | Sum | Action |
|---|---|---|---|
| -1 | 2 | 0 | Triplet found |
| 0 | 1 | 0 | Triplet found |
Join the conversation! Your thoughts help the community grow.