Skip to content

Instantly share code, notes, and snippets.

@konstantinvlasenko
Created January 11, 2020 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save konstantinvlasenko/57cdb6f0000295e97a17074f4a386252 to your computer and use it in GitHub Desktop.
Save konstantinvlasenko/57cdb6f0000295e97a17074f4a386252 to your computer and use it in GitHub Desktop.
3Sum JavaScript
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function(nums) {
nums.sort((a, b) => { return a - b; });
const result = [];
for (let i = 0; i < (nums.length-2); i ++) {
const a = nums[i];
if (a > 0) return result; // all other numbers to the right are positive as we are working with sorted array
if (i > 0 && a === nums[i - 1]) continue;
let start = i + 1;
let end = nums.length - 1;
while (start < end) {
const b = nums[start];
const c = nums[end];
if (a + b + c === 0) {
result.push([a,b,c]);
while (nums[end - 1] === c) { end--; }
while (nums[start + 1] === b) { start++; }
end--;
start++;
} else if (a + b + c > 0) {
end--;
} else {
start++;
}
}
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment