Three Sum Problem All Unique Triplets in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to find all unique triplets that sum to zero grows as the input list gets bigger.
How does the number of steps change when the list size increases?
Analyze the time complexity of the following code snippet.
function threeSum(nums) {
nums.sort((a, b) => a - b);
const result = [];
for (let i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue;
let left = i + 1, right = nums.length - 1;
while (left < right) {
const sum = nums[i] + nums[left] + nums[right];
if (sum === 0) {
result.push([nums[i], nums[left], nums[right]]);
while (nums[left] === nums[left + 1]) left++;
while (nums[right] === nums[right - 1]) right--;
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return result;
}
This code finds all unique triplets in the array that add up to zero by sorting and using a two-pointer approach.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The outer for-loop runs through each element, and inside it, the while-loop moves two pointers to find pairs.
- How many times: The outer loop runs about n times, and the inner while-loop runs up to n times in total for each outer loop step.
As the input size grows, the number of operations grows roughly with the square of the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 100 |
| 100 | About 10,000 |
| 1000 | About 1,000,000 |
Pattern observation: Doubling the input size roughly quadruples the work because of the nested loops.
Time Complexity: O(n²)
This means the time needed grows roughly with the square of the input size, so if the list doubles, the work increases about four times.
[X] Wrong: "Because there are three numbers, the time complexity must be O(n³)."
[OK] Correct: The sorting and two-pointer method reduce the inner search to linear time, so the total is O(n²), not cubic.
Understanding this time complexity helps you explain how efficient your solution is and shows you can optimize nested loops with smart techniques.
"What if we used three nested loops instead of sorting and two pointers? How would the time complexity change?"
Practice
Three Sum Problem in algorithms?Solution
Step 1: Understand the problem statement
The Three Sum Problem asks to find all unique sets of three numbers in an array whose sum is zero.Step 2: Differentiate from other sum problems
Unlike sorting or pair sums, this problem specifically targets triplets summing to zero without duplicates.Final Answer:
Find all unique triplets in an array that sum to zero -> Option AQuick Check:
Three Sum Problem = Find unique triplets summing to zero [OK]
- Confusing with pair sum problems
- Thinking it requires sorting only
- Looking for max sum instead of zero sum
nums in JavaScript before solving the Three Sum Problem?Solution
Step 1: Understand JavaScript sort behavior
By default,sort()converts elements to strings and sorts lexicographically, which is incorrect for numbers.Step 2: Use numeric comparator for ascending order
Usingnums.sort((a, b) => a - b)sorts numbers correctly in ascending order, which is needed for the algorithm.Final Answer:
nums.sort((a, b) => a - b) -> Option DQuick Check:
Numeric ascending sort = nums.sort((a, b) => a - b) [OK]
- Using default sort() without comparator
- Using descending sort when ascending needed
- Using non-existent method sorted()
function threeSum(nums) {
nums.sort((a, b) => a - b);
const result = [];
for (let i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue;
let left = i + 1, right = nums.length - 1;
while (left < right) {
const sum = nums[i] + nums[left] + nums[right];
if (sum === 0) {
result.push([nums[i], nums[left], nums[right]]);
while (nums[left] === nums[left + 1]) left++;
while (nums[right] === nums[right - 1]) right--;
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return result;
}
console.log(threeSum([-1,0,1,2,-1,-4]));Solution
Step 1: Sort the array
Sorted array is [-4, -1, -1, 0, 1, 2].Step 2: Find unique triplets summing to zero
Triplets found are [-1, -1, 2] and [-1, 0, 1]. These are pushed to result.Final Answer:
[[-1, -1, 2], [-1, 0, 1]] -> Option BQuick Check:
Unique triplets summing zero = [[-1,-1,2],[-1,0,1]] [OK]
- Not sorting before two-pointer approach
- Including duplicate triplets
- Incorrect pointer movement logic
function threeSum(nums) {
nums.sort((a, b) => a - b);
const result = [];
for (let i = 0; i < nums.length - 2; i++) {
if (nums[i] === nums[i - 1]) continue;
let left = i + 1, right = nums.length - 1;
while (left < right) {
const sum = nums[i] + nums[left] + nums[right];
if (sum === 0) {
result.push([nums[i], nums[left], nums[right]]);
while (nums[left] === nums[left + 1]) left++;
while (nums[right] === nums[right - 1]) right--;
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return result;
}Solution
Step 1: Check duplicate skipping condition
The conditionif (nums[i] === nums[i - 1]) continue;runs even when i = 0, causing incorrect skipping.Step 2: Correct condition to skip duplicates only if i > 0
It should beif (i > 0 && nums[i] === nums[i - 1]) continue;to avoid skipping first element.Final Answer:
The duplicate check for nums[i] should skip when i > 0 -> Option AQuick Check:
Duplicate skip needs i > 0 check [OK]
- Skipping duplicates without index check
- Wrong sorting comparator
- Forgetting to update pointers
nums = [3, 0, -2, -1, 1, 2], which of the following is the correct set of unique triplets that sum to zero?Solution
Step 1: Sort the array
Sorted array is [-2, -1, 0, 1, 2, 3].Step 2: Find all unique triplets summing to zero
Triplets are [-2, -1, 3], [-2, 0, 2], and [-1, 0, 1].Final Answer:
[[-2, -1, 3], [-2, 0, 2], [-1, 0, 1]] -> Option CQuick Check:
Sorted + two pointers find unique zero sum triplets [OK]
- Missing some triplets
- Including duplicates
- Incorrect triplet sums
Ready to prove it?
Pass the test and this pattern moves unknown
