Created
August 24, 2024 14:53
-
-
Save serhii-lypko/c1b3ae589c537f66e022f24972e3fcff to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function fourSum(nums: number[], target: number) { | |
| nums.sort((a, b) => a - b); | |
| let res: any = [], quad: any = []; | |
| // NOTE: better to use inner func since it has access to nums | |
| const kSum = (k, start, target) => { | |
| if (k != 2) { | |
| for (let i = start; i < nums.length - k + 1; i++) { | |
| if (i > start && nums[i - 1] == nums[i]) continue; | |
| quad.push(nums[i]); | |
| kSum(k - 1, i + 1, target - nums[i]); | |
| quad.pop(); | |
| } | |
| return; | |
| } | |
| // base case: Two Sum II | |
| let l = start, r = nums.length - 1; | |
| while (l < r) { | |
| if (nums[l] + nums[r] < target) { | |
| l++; | |
| } else if (nums[l] + nums[r] > target) { | |
| r--; | |
| } else { | |
| res.push([...quad, nums[l], nums[r]]); | |
| l++; | |
| while (l < r && nums[l] == nums[l - 1]) l++; | |
| } | |
| } | |
| } | |
| kSum(4, 0, target); | |
| return res; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment