15. 3Sum
Finding All Unique Triplets in an Array with Zero Sum
Problem Description
Given an integer array nums
, our goal is to return all unique triplets [nums[i], nums[j], nums[k]]
such that i != j
, i != k
, and j != k
, and nums[i] + nums[j] + nums[k] == 0
.
Intuition
To solve this problem, we need to find triplets in the array that sum up to zero. By sorting the array first, we can efficiently find these triplets using a two-pointer technique. Sorting the array also helps us easily skip duplicate elements and manage indices better.
Approach
Initial Check: If the array has fewer than 3 elements, return an empty list as no triplet can be formed.
Sorting: Sort the array in non-decreasing order, which helps in managing duplicates and using the two-pointer approach.
Iterate and Find Triplets:
Use a for-loop to iterate through the array, treating each element as the potential start of a triplet.
For each element, use two pointers (
startIndex
andendIndex
) to find pairs that, along with the current element, sum up to zero.Skip duplicate elements to ensure unique triplets.
Two-Pointer Technique:
Initialize two pointers:
startIndex
just after the current element andendIndex
at the end of the array.Calculate the total sum of the triplet.
If the sum is zero, store the triplet in the results list.
If the sum is less than zero, increment the
startIndex
to increase the sum.If the sum is greater than zero, decrement the
endIndex
to decrease the sum.Continue this process until the pointers meet.
Result: Return the list of unique triplets.
Complexity Analysis
Time Complexity: The time complexity is O(n^2) because sorting the array takes O(n log n) and the nested loop runs in O(n^2).
Space Complexity: The space complexity is O(1) for the input array and O(k) for the output list of triplets, where k is the number of triplets found.
LeetCode Solution
Check out my .
Code
function threeSum(nums) { let results = []; //check the size if(nums.length < 3) { return results; } // sort the array nums.sort((a,b) => a - b); // find the first value for(let i = 0; i < nums.length -2; i++) { // skip duplicates if (i > 0 && nums[i] === nums[i - 1]) { continue; } let startIndex = i + 1; let endIndex = nums.length - 1; while(startIndex < endIndex) { let total = nums[i] + nums[startIndex] + nums[endIndex]; if(0 === total) { results.push([nums[i],nums[startIndex],nums[endIndex]]); // skip duplicates while(nums[startIndex] === nums[startIndex + 1]){ startIndex++; } while(nums[endIndex] === nums[endIndex - 1]) { endIndex--; } // final updation startIndex++; endIndex--; }else if(total < 0) { startIndex++; }else{ endIndex--; } } } return results;}
I hope you find this guide helpful for understanding and implementing the threeSum
function. Feel free to share your thoughts or ask any questions! š
Comments
Post a Comment