|
| 1 | +// Time Complexity: O(n^2) |
| 2 | +// Space Complexity: O(n) |
| 3 | + |
| 4 | +// Time Complexity: O(n^2) |
| 5 | +// Space Complexity: O(n) |
| 6 | + |
| 7 | +var threeSum = function(nums) { |
| 8 | + nums.sort((a, b) => a - b); |
| 9 | + // create a set to store triplets. |
| 10 | + const result = new Set(); |
| 11 | + |
| 12 | + // loop through the array, but stop 2 elements before the end. |
| 13 | + for (let i = 0; i < nums.length - 2; i++) { |
| 14 | + // if the current element is the same as the one before it, skip it to avoid duplicates. |
| 15 | + if (i > 0 && nums[i] === nums[i - 1]) continue; |
| 16 | + |
| 17 | + // create a set to keep track of the complements. |
| 18 | + const complements = new Set(); |
| 19 | + // start another loop from the next element. |
| 20 | + for (let j = i + 1; j < nums.length; j++) { |
| 21 | + const complement = -nums[i] - nums[j]; |
| 22 | + // check if the current number is in the set. |
| 23 | + if (complements.has(nums[j])) { |
| 24 | + // if it is, found a triplet. Add it to the result set as a sorted string to avoid duplicates. |
| 25 | + result.add(JSON.stringify([nums[i], complement, nums[j]].sort((a, b) => a - b))); |
| 26 | + } else { |
| 27 | + complements.add(complement); |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + // convert set of strings back to arrays. |
| 33 | + return Array.from(result).map(triplet => JSON.parse(triplet)); |
| 34 | +}; |
0 commit comments