Skip to content

Commit

Permalink
Merge pull request #207 from Ahtaxam/master
Browse files Browse the repository at this point in the history
Add 3-sum problem with improvement issue #208
  • Loading branch information
ashokdey committed Jun 18, 2023
2 parents 56fb83e + 75a9df6 commit d62e62c
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
2 changes: 1 addition & 1 deletion TOC.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
39 changes: 39 additions & 0 deletions src/_Problems_/3Sum/3sum.js
Original file line number Diff line number Diff line change
@@ -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;

19 changes: 19 additions & 0 deletions src/_Problems_/3Sum/3sum.test.js
Original file line number Diff line number Diff line change
@@ -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]]);
});

});

0 comments on commit d62e62c

Please sign in to comment.