#15
3Sum
MediumArrayTwo PointersSortingHash MapArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution (Two Pointers)★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n²)Space O(1)
By sorting the array first, we can use a two-pointer technique to find pairs that sum to a specific value, which allows us to efficiently find triplets that sum to zero.
⚙️
Algorithm
3 steps- 1Step 1: Sort the array.
- 2Step 2: Iterate through the array, fixing one element at a time.
- 3Step 3: Use two pointers to find pairs that sum to the negative of the fixed element.
solution.py28 lines
1# Full working Python code with comments
2
3def three_sum(nums):
4 nums.sort()
5 result = []
6 n = len(nums)
7 for i in range(n):
8 if i > 0 and nums[i] == nums[i - 1]:
9 continue # Skip duplicates
10 left, right = i + 1, n - 1
11 while left < right:
12 total = nums[i] + nums[left] + nums[right]
13 if total < 0:
14 left += 1
15 elif total > 0:
16 right -= 1
17 else:
18 result.append([nums[i], nums[left], nums[right]])
19 while left < right and nums[left] == nums[left + 1]:
20 left += 1 # Skip duplicates
21 while left < right and nums[right] == nums[right - 1]:
22 right -= 1 # Skip duplicates
23 left += 1
24 right -= 1
25 return result
26
27# Example usage
28print(three_sum([-1, 0, 1, 2, -1, -4]))ℹ
Complexity note: The time complexity remains O(n²) due to the nested loop for the two-pointer approach. The space complexity is O(1) since we are using only a constant amount of extra space.
- 1Sorting the array allows us to efficiently use the two-pointer technique, which reduces the number of checks needed for pairs.
- 2Skipping duplicates is crucial in both the brute force and optimal solutions to ensure unique triplets.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.