Skip to content

Instantly share code, notes, and snippets.

@AfJalili
Created July 2, 2023 22:59
Show Gist options
  • Save AfJalili/c2bfbd7e66d8497af2abd2fa91153c4a to your computer and use it in GitHub Desktop.
Save AfJalili/c2bfbd7e66d8497af2abd2fa91153c4a to your computer and use it in GitHub Desktop.
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