The 3Sum Problem: $O(n^2)$ Time and $O(1)$ Auxiliary Space
To find all unique triplets $[a, b, c]$ such that $a + b + c = 0$ without using an auxiliary hash set to track duplicates, sort the array first and combine a fixed anchor pointer with a two-pointer sweep. Duplicates are bypassed directly in-place by skipping adjacent identical values.
Algorithmic Strategy
- Sort the Array: Sorting takes $O(n \log n)$ time and brings identical elements together, which enables trivial in-place duplicate filtering.
- Anchor Outer Loop (
i): Iterate from index0up ton - 3. Ifarr[i] > 0, terminate early because the remaining sorted elements cannot sum to zero. Skip iteration ifarr[i] == arr[i - 1]to prevent duplicate triplets from the same anchor. - Two-Pointer Search (
left&right): Setleft = i + 1andright = n - 1. Calculatesum = arr[i] + arr[left] + arr[right]:- If
sum == 0: Record the triplet. Advanceleftwhilearr[left] == arr[left + 1]and retreatrightwhilearr[right] == arr[right - 1]to purge duplicate components, then move both pointers inward once more. - If
sum < 0: Incrementleftto increase the total sum. - If
sum > 0: Decrementrightto decrease the total sum.
- If
Complexity Analysis
| Metric | Complexity | Explanation |
|---|---|---|
| Time Complexity | $O(n^2)$ | Sorting takes $O(n \log n)$. The outer loop runs $n$ times; each iteration executes a linear two-pointer scan taking $O(n)$. Thus, $O(n \log n) + O(n^2) = O(n^2)$. |
| Auxiliary Space | $O(1)$ | No hash sets or lookup buffers are created. Only pointers and loop index primitives are stored (excluding the return output and sorting stack space). |
Complete Implementation (C++ & Python)
C++ Implementation
#include <vector>
#include <algorithm>
std::vector<std::vector<int>> threeSum(std::vector<int>& nums) {
std::vector<std::vector<int>> result;
int n = nums.size();
if (n < 3) return result;
// In-place sort to enable two-pointer traversal
std::sort(nums.begin(), nums.end());
for (int i = 0; i < n - 2; ++i) {
// Optimization: Smallest element > 0 means sum cannot be 0
if (nums[i] > 0) break;
// Skip duplicates for the anchor element
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1;
int right = n - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
result.push_back({nums[i], nums[left], nums[right]});
// Skip duplicates for left pointer
while (left < right && nums[left] == nums[left + 1]) left++;
// Skip duplicates for right pointer
while (left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return result;
}
Python Implementation
def three_sum(nums: list[int]) -> list[list[int]]:
nums.sort()
result = []
n = len(nums)
for i in range(n - 2):
# Optimization: sorted list with anchor > 0 cannot yield sum == 0
if nums[i] > 0:
break
# Skip duplicate anchor elements
if i > 0 and nums[i] == nums[i - 1]:
continue
left, right = i + 1, n - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total == 0:
result.append([nums[i], nums[left], nums[right]])
# Skip adjacent duplicates without hash sets
while left < right and nums[left] == nums[left + 1]:
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
left += 1
right -= 1
elif total < 0:
left += 1
else:
right -= 1
return result
Critical In-Place Deduplication Logic
- Anchor check:
nums[i] == nums[i - 1]ensures the first appearance of a number handles all possible pairings; subsequent identical numbers are ignored. - Inner check: After finding a match, the
whileloops move past all identical values for bothleftandright. Advancing both pointers once more guarantees the next pair inspected consists of distinct values without allocating secondary tracking sets.
You must log in or register to comment.
