Skip to content

Commit

Permalink
3sum solution
Browse files Browse the repository at this point in the history
  • Loading branch information
yoon-turtle committed Jan 11, 2025
1 parent 977921d commit fd476db
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions 3sum/yoonthecoder.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
var threeSum = function (nums) {
nums.sort((a, b) => a - b);
const results = [];
for (let i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue;
let left = i + 1;
let right = nums.length - 1;
while (left < right) {
const currSum = nums[i] + nums[left] + nums[right];

if (currSum == 0) {
results.push([nums[i], nums[left], nums[right]]);
left++;
right--;
// to avoid duplicates
while (left < right && nums[left] === nums[left - 1]) left++;
while (left < right && nums[right] === nums[right + 1]) right--;
} else if (currSum < 0) {
left++;
} else right--;
}
}
return results;
};

// Time complexity: O(n^2);
// Space complexity: O(n)

0 comments on commit fd476db

Please sign in to comment.