Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add 3sum problem #207

Merged
merged 4 commits into from
Jun 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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]]);
});

});