15. 3Sum
🟧 Medium
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]]
such that i != j
, i != k
, and j != k
, and nums[i] + nums[j] + nums[k] == 0
.
Notice that the solution set must not contain duplicate triplets.
Example 1
Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Explanation: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter.
Example 2
Input: nums = [0,1,1] Output: [] Explanation: The only possible triplet does not sum up to 0.
Example 3
Input: nums = [0,0,0] Output: [[0,0,0]] Explanation: The only possible triplet sums up to 0.
Hint-1
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand!
Hint-2
For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y, which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster?
Hint-3
The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
Constraints
3 <= nums.length <= 3000
-10^5 <= nums[i] <= 10^5
Solution
My Solution
Optimal Solution
The optimal solution uses two key techniques:
Sorting for duplicate handling and efficient searching
Two-pointer technique for finding pairs that sum to target
Here's an optimized version with improved readability and performance:
Approach Analysis
The solution employs three main techniques:
Sorting:
Makes duplicate handling efficient
Enables two-pointer technique
Allows for early termination
Two-Pointer Technique:
Uses sorted array property
Efficiently finds pairs summing to target
Reduces time complexity from O(n²) to O(n)
Duplicate Handling:
Skip duplicates for first number
Skip duplicates for second and third numbers
Ensures unique triplets
Visualization of Both Approaches
Complexity Analysis
Time Complexity:
Sorting: O(n log n)
Two pointers: O(n²)
Overall: O(n²)
Space Complexity:
Result array: O(k) where k is number of valid triplets
Sorting space: O(log n) to O(n) depending on sort implementation
Overall: O(k)
Optimizations:
Early termination when first number > 0
Skip duplicates to avoid redundant calculations
Two-pointer technique instead of nested loops
Why Solution Works
Sorting Enables Efficiency:
Makes duplicate detection simple
Allows two-pointer technique
Enables early termination
Two-Pointer Logic:
If sum too small, increase left pointer
If sum too large, decrease right pointer
Guarantees finding all valid pairs
Duplicate Handling:
Sorting puts duplicates adjacent
Skip duplicates for all three positions
Ensures unique triplets in result
When to Use
This approach is ideal when:
Need to find all combinations summing to target
Duplicates need to be handled
Order of triplets doesn't matter
Input array can be modified
Common variations:
4Sum problem
K-sum problem
Two-pointer problems
Combination sum problems
Common Patterns & Applications
Two-Pointer Pattern:
Sorted array traversal
Meeting in middle
Opposite direction movement
Sorting + Two Pointers:
Finding combinations
Handling duplicates
Range-based problems
Sum Problems:
TwoSum variations
KSum problems
Target sum problems
Interview Tips
Key Discussion Points:
Why sorting first?
How to handle duplicates?
Time/space complexity tradeoffs
Optimization techniques
Common Follow-up Questions:
How to handle 4Sum?
Can we do it without sorting?
How to optimize for specific input patterns?
How to handle negative targets?
Edge Cases to Consider:
Empty array
Array with < 3 elements
All zeros
All same numbers
No valid triplets
Optimization Opportunities:
Early termination
Duplicate skipping
Memory management
Input validation
Last updated
Was this helpful?