Skip to content
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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,5 @@
- [Task #9](src/neetcode/arrays-&-hashing/longest-consecutive-sequence) - _Longest Consecutive Sequence_ - _[check the task](https://neetcode.io/problems/longest-consecutive-sequence)_
- Two Pointers
- [Task #10](src/neetcode/two-pointers/valid-palindrome) - _Valid Palindrome_ - _[check the task](https://neetcode.io/problems/is-palindrome)_
- [Task #11](src/neetcode/two-pointers/two-sum-ii-input-array-is-sorted) - _Two Sum II Input Array Is Sorted_ - _[check the task](https://neetcode.io/problems/two-integer-sum-ii)_
- [Task #11](src/neetcode/two-pointers/two-sum-ii-input-array-is-sorted) - _Two Sum II Input Array Is Sorted_ - _[check the task](https://neetcode.io/problems/two-integer-sum-ii)_
- [Task #12](src/neetcode/two-pointers/3sum) - _3Sum_ - _[check the task](https://neetcode.io/problems/three-integer-sum)_
27 changes: 27 additions & 0 deletions src/neetcode/two-pointers/3sum/solution.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { threeSum } from './solution';

describe('3Sum | NeetCode | RoadMap | Testcases', () => {
test('#1 Some triplets', () => {
const nums = [-1, 0, 1, 2, -1, -4];
const expected = [
[-1, -1, 2],
[-1, 0, 1],
];
const output = threeSum(nums);
expect(output).toEqual(expected);
});

test('#2 No triplets', () => {
const nums = [0, 1, 1];
const expected: number[][] = [];
const output = threeSum(nums);
expect(output).toEqual(expected);
});

test('#3 One triplet', () => {
const nums = [0, 0, 0];
const expected: number[][] = [[0, 0, 0]];
const output = threeSum(nums);
expect(output).toEqual(expected);
});
});
38 changes: 38 additions & 0 deletions src/neetcode/two-pointers/3sum/solution.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* @param {number[]} nums - an integer array
* @return {number[][]} - all the triplets `[nums[i], nums[j], nums[k]]` where `nums[i] + nums[j] + nums[k] == 0`,
* and the indices `i, j, k` are all distinct.
*/
export const threeSum = (nums: number[]): number[][] => {
const res: number[][] = [];
nums.sort((a, b) => a - b);

for (let i = 0; i < nums.length; i++) {
if (nums[i] > 0) {
break;
}
if (i > 0 && nums[i] === nums[i - 1]) {
continue;
}

let l = i + 1;
let r = nums.length - 1;

while (l < r) {
const sum = nums[i] + nums[l] + nums[r];
if (sum > 0) {
r--;
} else if (sum < 0) {
l++;
} else {
res.push([nums[i], nums[l], nums[r]]);
l++;
r--;
while (l < r && nums[l] === nums[l - 1]) {
l++;
}
}
}
}
return res;
};
Loading