Created
July 2, 2023 22:59
-
-
Save AfJalili/c2bfbd7e66d8497af2abd2fa91153c4a to your computer and use it in GitHub Desktop.
This file contains 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 findOrderedPairs(arr: number[], sum: number) { | |
const result: number [][] = []; | |
arr.sort((a ,b) => a - b); | |
let low = 0, high = arr.length - 1; | |
while (low < high) { | |
if (arr[low] + arr[high] < sum) { | |
low++; | |
} else if (arr[low] + arr[high] > sum) { | |
high--; | |
} else { | |
result.push([arr[low], arr[high]]); | |
result.push([arr[high], arr[low]]); | |
let runner = low + 1; | |
while (runner < high && arr[runner] === arr[low]) { | |
result.push([arr[runner], arr[high]]); | |
result.push([arr[high], arr[runner]]); | |
runner++; | |
} | |
high--; | |
} | |
} | |
return result; | |
} | |
console.log(findOrderedPairs([1, 3, 3, 3], 6)); | |
// output: [ [ 3, 3 ], [ 3, 3 ], [ 3, 3 ], [ 3, 3 ], [ 3, 3 ], [ 3, 3 ] ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment