Skip to content

Commit d62e62c

Browse files
authoredJun 18, 2023
Merge pull request knaxus#207 from Ahtaxam/master
Add 3-sum problem with improvement issue knaxus#208
2 parents 56fb83e + 75a9df6 commit d62e62c

File tree

3 files changed

+59
-1
lines changed

3 files changed

+59
-1
lines changed
 

‎TOC.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@
7676
- [Next Greater for Every Element in an Array](src/_Problems_/next-greater-element)
7777
- [Compose Largest Number](src/_Problems_/compose-largest-number)
7878
- [Rotate Image](src/_Problems_/rotate-image)
79-
79+
- [3 Sum](src/_Problems_/3Sum/)
8080
### Searching
8181

8282
- [Binary Search](src/_Searching_/BinarySearch)

‎src/_Problems_/3Sum/3sum.js

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
const threeSum = function(nums) {
2+
// sort the array
3+
nums = nums.sort((a, b) => a - b);
4+
5+
let result = [];
6+
// iterate through the array and use two pointers to find the sum
7+
for (let i = 0; i < nums.length; ++i) {
8+
let left = i + 1;
9+
let right = nums.length - 1;
10+
while (left < right) {
11+
let sum = nums[i] + nums[left] + nums[right];
12+
if (sum == 0) {
13+
result.push([nums[i], nums[left], nums[right]]);
14+
left++;
15+
right--;
16+
}
17+
else if (sum < 0) {
18+
left++;
19+
}
20+
else {
21+
right--;
22+
}
23+
}
24+
// skip duplicates
25+
while (i < nums.length - 1 && nums[i] == nums[i + 1]) {
26+
i++;
27+
}
28+
}
29+
30+
// initialize set to remove duplicate
31+
const set = new Set(result.map(JSON.stringify));
32+
// final output array
33+
output = (new Array(...set).map(JSON.parse));
34+
return output;
35+
};
36+
37+
38+
module.exports = threeSum;
39+

‎src/_Problems_/3Sum/3sum.test.js

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const threeSum = require("./3sum");
2+
3+
describe("threeSum", () => {
4+
it("Should return [[-1, -1, 2], [-1, 0, 1]]", () => {
5+
expect(threeSum([-1, 0, 1, 2, -1, -4])).toEqual([
6+
[-1, -1, 2],
7+
[-1, 0, 1],
8+
]);
9+
});
10+
11+
it("Should return [[0, 0, 0]]", () => {
12+
expect(threeSum([0, 0, 0])).toEqual([[0, 0, 0]]);
13+
});
14+
15+
it("Should return [[-1, -1, 2]]", () => {
16+
expect(threeSum([-1, 2, -1, -4])).toEqual([[-1, -1, 2]]);
17+
});
18+
19+
});

0 commit comments

Comments
 (0)
Please sign in to comment.