Problem Statement
Given an integer array nums
, return all the triplets [nums[i], nums[j], nums[k]]
such that:
- i != j
- i != k
- j != k
nums[i] + nums[j] + nums[k] == 0
.
The solution set must not contain duplicate triplets.
Example Test Cases
Example 1
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Example 2
Input: nums = [0,1,1]
Output: []
Example 3
Input: nums = [0,0,0]
Output: [[0, 0, 0]]
Approaches
Brute Force Approach
Idea
We can try all possible triplet combinations and check if their sum equals zero. This would involve nested loops to pick each triplet.
Steps
- Iterate through the array using three nested loops.
- Check if the sum of each triplet equals 0.
- Collect all unique triplets that satisfy the condition.
Time Complexity
- O(n^3): Three nested loops iterating through the array.
Space Complexity
Code
Dry Run
Given nums = [-1, 0, 1, 2, -1, -4]
, it checks all possible triplets and finds [-1, -1, 2]
and [-1, 0, 1]
.
Efficient Approach: Two Pointer Technique
Idea
First, sort the array. Then for each element, use the two-pointer technique to find the other two elements that sum to zero. Sorting helps avoid duplicate triplets.
Steps
- Sort the input array.
- Fix one number, and for the remaining two numbers, use the two-pointer technique to find the target sum (which would be the negative of the fixed number).
- Skip duplicates to ensure unique triplets.
Time Complexity
- O(n^2): We iterate through the array and use two-pointer search.
Space Complexity
- O(1) for extra space (excluding the result).
Code
Dry Run
For nums = [-1, 0, 1, 2, -1, -4]
, after sorting, the algorithm finds [-1, -1, 2]
and [-1, 0, 1]
.
Example Test Case
Test Case 1
Test Case 2
Test Case 3
Complexity Analysis
Brute Force Approach
- Time Complexity: O(n^3)
- Space Complexity: O(1)
Efficient Approach
- Time Complexity: O(n^2) (due to sorting and two-pointer technique)
- Space Complexity: O(1)
Conclusion
The two-pointer technique offers a more efficient solution with O(n^2) time complexity, significantly reducing the number of unnecessary comparisons and avoiding duplicate triplets compared to the brute force method.