Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1899 from andynullwong/0018
Browse files Browse the repository at this point in the history
Create 0018-4sum.js & .ts
  • Loading branch information
tahsintunan authored Jan 8, 2023
2 parents 75aac3b + 7b0cfd2 commit b97ccc9
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 0 deletions.
48 changes: 48 additions & 0 deletions javascript/0018-4sum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* @param {number[]} nums
* @param {number} target
* @return {number[][]}
*/
var fourSum = function (nums, target) {
const sortedNums = nums.sort((a, b) => a - b);
const res = [];
const quad = [];

const kSum = (k, start, target) => {
if (k > 2) {
for (let i = start; i < sortedNums.length; i++) {
if (i !== start && sortedNums[i] === sortedNums[i - 1]) {
continue;
}
quad.push(sortedNums[i]);
kSum(k - 1, i + 1, target - sortedNums[i]);
quad.pop();
}
} else {
let left = start;
let right = sortedNums.length - 1;

while (left < right) {
const sum = sortedNums[left] + sortedNums[right];
if (sum < target) {
left++;
} else if (sum > target) {
right--;
} else {
res.push(
quad.concat([sortedNums[left], sortedNums[right]])
);
left++;
while (
left < right &&
sortedNums[left] === sortedNums[left - 1]
) {
left++;
}
}
}
}
};
kSum(4, 0, target);
return res;
};
43 changes: 43 additions & 0 deletions typescript/0018-4sum.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
function fourSum(nums: number[], target: number): number[][] {
const sortedNums: number[] = nums.sort((a: number, b: number) => a - b);
const res: number[][] = [];
const quad: number[] = [];

const kSum = (k: number, start: number, target: number): void => {
if (k > 2) {
for (let i = start; i < sortedNums.length; i++) {
if (i !== start && sortedNums[i] === sortedNums[i - 1]) {
continue;
}
quad.push(sortedNums[i]);
kSum(k - 1, i + 1, target - sortedNums[i]);
quad.pop();
}
} else {
let left: number = start;
let right: number = sortedNums.length - 1;

while (left < right) {
const sum = sortedNums[left] + sortedNums[right];
if (sum < target) {
left++;
} else if (sum > target) {
right--;
} else {
res.push(
quad.concat([sortedNums[left], sortedNums[right]])
);
left++;
while (
left < right &&
sortedNums[left] === sortedNums[left - 1]
) {
left++;
}
}
}
}
};
kSum(4, 0, target);
return res;
}

0 comments on commit b97ccc9

Please sign in to comment.