Created
July 22, 2023 08:39
-
-
Save vousmeevoyez/c6505fb55f6bea32d7e61211edf095f8 to your computer and use it in GitHub Desktop.
Find Pairs with Sum
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 findPairsWithSum(arr, target) { | |
// to store paris | |
const pairs = []; | |
// to store seen number with their index | |
const seenNum = {}; | |
for (let i = 0; i < arr.length; i++) { | |
// calculate the complement / pair by deducting the current number with target | |
const complement = target - arr[i]; | |
// to prevent duplicate | |
// if complement seen then add it to pairs | |
if(seenNum[complement] !== undefined){ | |
pairs.push([arr[i], complement]) | |
} | |
seenNum[arr[i]] = i | |
} | |
return pairs; | |
} | |
const testCases = [ | |
{ | |
arr: [2, 7, 4, 0, 9, 5, 1, 3], | |
target: 7, | |
expected_length: 3 | |
}, | |
{ | |
arr: [0, 0, 0, 0, 0, 0, 0, 0], | |
target: 7, | |
expected_length: 0 | |
}, | |
{ | |
arr: [2, 7, 4, 0, 9, 5, 1, 3], | |
target: 10, | |
expected_length: 2 | |
}, | |
] | |
testCases.forEach(({arr, target, expected_length}) => { | |
const result = findPairsWithSum(arr, target) | |
console.log(result) | |
console.log(result.length === expected_length) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment