Algorithm-Day06-3Sum-lc#15
🧩 Problem Description
Given an integer array nums
, return all the triplets [nums[i], nums[j], nums[k]]
such that i != j != k
and nums[i] + nums[j] + nums[k] == 0
.
Note: The solution must not contain duplicate triplets.
Example:
1 | Input: nums = [-1,0,1,2,-1,-4] |
💡 Brute Force (Too Slow)
Try all triplets (i, j, k)
and check if the sum is 0.
- Time complexity is O(n³)
- May also return duplicate triplets
- ❌ Not acceptable for large input sizes
💡 Optimal Approach (Two Pointers After Sorting)
- Sort the array
- Fix one element
nums[i]
- Use two pointers
left
andright
to find pairs that sum to-nums[i]
- Skip duplicates to ensure unique triplets
🔢 Java Code
1 | class Solution { |
⏱ Time and Space Complexity
- Time Complexity: O(n²)
- Outer loop O(n), inner loop O(n)
- Space Complexity: O(1) (excluding the output list)
✍️ Summary
- A classic example of combining sorting + two pointers
- Always handle duplicates carefully when problems ask for “unique” results
- This technique is often reused in 4Sum, Two Sum II, etc.
Understanding this pattern gives you a powerful tool for many array + sum problems.