15. 3Sum - Detailed Explanation
Problem Statement
Description:
Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] such that:
- ( nums[i] + nums[j] + nums[k] = 0 )
- ( i ), ( j ), and ( k ) are distinct indices.
Note:
- The solution set must not contain duplicate triplets.
- The order of the triplets in the output does not matter.
Example Inputs, Outputs, and Explanations
- 
Example 1: - Input: nums = [-1, 0, 1, 2, -1, -4]
- Output: [[-1, -1, 2], [-1, 0, 1]]
- Explanation:
- The triplets that sum to zero are:
- (-1 + (-1) + 2 = 0)
- (-1 + 0 + 1 = 0)
 
- Notice that duplicate triplets are not allowed.
 
- The triplets that sum to zero are:
 
- Input: 
- 
Example 2: - Input: nums = []
- Output: []
- Explanation:
- An empty array does not contain any triplets.
 
 
- Input: 
- 
Example 3 (Edge Case): - Input: nums = [0]
- Output: []
- Explanation:
- With fewer than three elements, no triplet can be formed.
 
 
- Input: 
Constraints
- ( 0 \leq \text{nums.length} \leq 3000 )
- ( -10^5 \leq \text{nums}[i] \leq 10^5 )
Hints to Approach the Solution
- 
Sorting Is Key: - Sorting the array helps to avoid duplicates and makes it easier to use two pointers to find pairs that sum to a specific target.
 
- 
Two-Pointer Technique: - For each element ( nums[i] ) in the sorted array, use two pointers (one starting just after ( i ) and one at the end) to search for a pair such that their sum equals ( -nums[i] ).
 
- 
Skip Duplicates: - To ensure unique triplets, skip over duplicate elements when iterating through the array and when moving the two pointers.
 
Approach 1: Brute Force (Not Recommended)
Explanation
- Method:
- Use three nested loops to check every possible triplet in the array.
 
- Drawbacks:
- Time complexity is ( O(n^3) ), which is not efficient for larger arrays.
 
Approach 2: Sorting with Two-Pointer Technique (Optimal)
Explanation
- Step 1: Sort the Array
- Sorting helps in identifying duplicates and simplifies the two-pointer search.
 
- Step 2: Iterate Through the Array
- For each index ( i ) (from 0 to ( n-3 )):
- If ( i > 0 ) and ( nums[i] ) is the same as ( nums[i-1] ), skip it to avoid duplicates.
 
 
- For each index ( i ) (from 0 to ( n-3 )):
- Step 3: Two-Pointer Search
- Initialize two pointers:
- ( \text{left} = i + 1 )
- ( \text{right} = n - 1 )
 
- While ( \text{left} < \text{right} ):
- Compute ( \text{sum} = nums[i] + nums[left] + nums[right] )
- If ( \text{sum} == 0 ):
- Add the triplet to the result.
- Skip duplicates for both ( \text{left} ) and ( \text{right} ).
- Move both pointers inward.
 
- If ( \text{sum} < 0 ):
- Increase ( \text{left} ) (to add a larger number).
 
- If ( \text{sum} > 0 ):
- Decrease ( \text{right} ) (to add a smaller number).
 
 
 
- Initialize two pointers:
Pseudocode
sort(nums)
result = []
for i from 0 to len(nums) - 3:
    if i > 0 and nums[i] == nums[i - 1]:
        continue
    left = i + 1, right = len(nums) - 1
    while left < right:
        sum = nums[i] + nums[left] + nums[right]
        if sum == 0:
            add triplet [nums[i], nums[left], nums[right]] to result
            while left < right and nums[left] == nums[left + 1]:
                left++
            while left < right and nums[right] == nums[right - 1]:
                right--
            left++, right--
        else if sum < 0:
            left++
        else:
            right--
return result
Code Implementations
Python Code
Python3
Python3
. . . .
Java Code
Java
Java
. . . .
Complexity Analysis
- 
Time Complexity: - Sorting the array takes ( O(n \log n) ).
- The main loop runs in ( O(n^2) ) in the worst case (using two pointers inside the loop).
- Overall: ( O(n^2) ).
 
- 
Space Complexity: - ( O(1) ) extra space aside from the space needed to store the output.
- Sorting is typically done in-place.
 
Step-by-Step Walkthrough (Visual Example)
Consider the input:
nums = [-1, 0, 1, 2, -1, -4]
- 
Sort the Array: 
 Sortednums = [-4, -1, -1, 0, 1, 2].
- 
Iteration: - i = 0: ( nums[0] = -4 )
- Set ( left = 1 ) and ( right = 5 ).
- Check sum: (-4 + (-1) + 2 = -3) (less than 0) → move left pointer.
- Continue: (-4 + (-1) + 2 = -3) → still less than 0.
- No valid triplet found for ( i = 0 ).
 
- i = 1: ( nums[1] = -1 )
- Set ( left = 2 ) and ( right = 5 ).
- Check sum: (-1 + (-1) + 2 = 0) → valid triplet found: ([-1, -1, 2]).
- Skip duplicate for ( left ) and move pointers.
- Next, check: (-1 + 0 + 1 = 0) → valid triplet found: ([-1, 0, 1]).
 
 
- i = 0: ( nums[0] = -4 )
- 
Result: 
 The valid triplets found are:
 ([[-1, -1, 2], [-1, 0, 1]]).
Common Mistakes & Edge Cases
Common Mistakes
- Duplicates:
- Failing to skip over duplicates when moving the pointers or iterating the main loop may lead to repeated triplets.
 
- Pointer Mismanagement:
- Incorrectly updating the ( left ) and ( right ) pointers might result in missing valid triplets or including invalid ones.
 
- Boundary Conditions:
- Not handling arrays with fewer than three elements correctly.
 
Edge Cases
- Empty Array or Array with Fewer than 3 Elements:
- Return an empty list.
 
- All Zeros:
- Ensure only one triplet ([0, 0, 0]) is returned, even if there are multiple zeros.
 
- No Valid Triplet:
- If no triplet sums to zero, return an empty list.
 
Alternative Variations and Related Problems
Variations
- 4Sum:
- Find all unique quadruplets that sum up to a target value.
 
- 3Sum Closest:
- Find the triplet whose sum is closest to a given target.
 
Related Problems for Further Practice
- 4Sum
- 3Sum Closest
- Two Sum
TAGS
leetcode
CONTRIBUTOR
Design Gurus Team
-
GET YOUR FREE
Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
2558. Take Gifts From the Richest Pile - Detailed Explanation
Learn to solve Leetcode 2558. Take Gifts From the Richest Pile with multiple approaches.
836. Rectangle Overlap - Detailed Explanation
Learn to solve Leetcode 836. Rectangle Overlap with multiple approaches.
1574. Shortest Subarray to be Removed to Make Array Sorted - Detailed Explanation
Learn to solve Leetcode 1574. Shortest Subarray to be Removed to Make Array Sorted with multiple approaches.
2008. Maximum Earnings From Taxi - Detailed Explanation
Learn to solve Leetcode 2008. Maximum Earnings From Taxi with multiple approaches.
736. Parse Lisp Expression - Detailed Explanation
Learn to solve Leetcode 736. Parse Lisp Expression with multiple approaches.
127. Word Ladder - Detailed Explanation
Learn to solve Leetcode 127. Word Ladder with multiple approaches.
Related Courses
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
4.6
(69,299 learners)
$197
New

Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
3.9
(1,107 learners)
$78
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
4
(26,683 learners)
$78
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.