diff --git a/README.md b/README.md index 251e7e1..81e7c9d 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,6 @@ Find the detailed contents and problem list here: [Table Of Contents](TOC.md) ## Contribution Guide -It's great to know that you want to contribute to this repo. Thanks for taking interest. please find the [guide here](https://github.com/knaxus/problem-solving-javascript/blob/master/CONTRIBUTING.md) +It's great to know that you want to contribute to this repo. Thanks for taking interest. Please find the [guide here](https://github.com/knaxus/problem-solving-javascript/blob/master/CONTRIBUTING.md) -Keep an eye on this guide, it's subjected to change frequently. +Keep an eye on this guide. It's subject to frequent change. diff --git a/TOC.md b/TOC.md index 7765ff7..5824855 100644 --- a/TOC.md +++ b/TOC.md @@ -76,7 +76,7 @@ - [Next Greater for Every Element in an Array](src/_Problems_/next-greater-element) - [Compose Largest Number](src/_Problems_/compose-largest-number) - [Rotate Image](src/_Problems_/rotate-image) - +- [3 Sum](src/_Problems_/3Sum/) ### Searching - [Binary Search](src/_Searching_/BinarySearch) diff --git a/src/_Problems_/3Sum/3sum.js b/src/_Problems_/3Sum/3sum.js new file mode 100644 index 0000000..6e7f536 --- /dev/null +++ b/src/_Problems_/3Sum/3sum.js @@ -0,0 +1,39 @@ +const threeSum = function(nums) { + // sort the array + nums = nums.sort((a, b) => a - b); + + let result = []; + // iterate through the array and use two pointers to find the sum + for (let i = 0; i < nums.length; ++i) { + let left = i + 1; + let right = nums.length - 1; + while (left < right) { + let sum = nums[i] + nums[left] + nums[right]; + if (sum == 0) { + result.push([nums[i], nums[left], nums[right]]); + left++; + right--; + } + else if (sum < 0) { + left++; + } + else { + right--; + } + } + // skip duplicates + while (i < nums.length - 1 && nums[i] == nums[i + 1]) { + i++; + } + } + + // initialize set to remove duplicate + const set = new Set(result.map(JSON.stringify)); + // final output array + output = (new Array(...set).map(JSON.parse)); + return output; +}; + + +module.exports = threeSum; + diff --git a/src/_Problems_/3Sum/3sum.test.js b/src/_Problems_/3Sum/3sum.test.js new file mode 100644 index 0000000..ad1114e --- /dev/null +++ b/src/_Problems_/3Sum/3sum.test.js @@ -0,0 +1,19 @@ +const threeSum = require("./3sum"); + +describe("threeSum", () => { + it("Should return [[-1, -1, 2], [-1, 0, 1]]", () => { + expect(threeSum([-1, 0, 1, 2, -1, -4])).toEqual([ + [-1, -1, 2], + [-1, 0, 1], + ]); + }); + + it("Should return [[0, 0, 0]]", () => { + expect(threeSum([0, 0, 0])).toEqual([[0, 0, 0]]); + }); + + it("Should return [[-1, -1, 2]]", () => { + expect(threeSum([-1, 2, -1, -4])).toEqual([[-1, -1, 2]]); + }); + +});