Skip to content

Instantly share code, notes, and snippets.

@anushshukla
Created March 2, 2023 15:11
Show Gist options
  • Select an option

  • Save anushshukla/78b1b23da83bb2c0699975a798176ff8 to your computer and use it in GitHub Desktop.

Select an option

Save anushshukla/78b1b23da83bb2c0699975a798176ff8 to your computer and use it in GitHub Desktop.
Given an unsorted integer array, find a pair with the given sum in it.
/*
For example,
Input:
nums = [8, 7, 2, 5, 3, 1]
target = 10
Output:
Pair found (8, 2)
or
Pair found (7, 3)
Input:
nums = [5, 2, 6, 8, 1, 9]
target = 12
Output: Pair not found
*/
function getTargetIndexes(input) {
const { array, target } = input;
const hash = {};
const results = [];
for (let i = 0; i < array.length; i++) {
const value = array[i];
const pairReqdNum = target - value;
const pairReqdIndex = hash[pairReqdNum];
if (typeof pairReqdIndex !== 'undefined') {
results.push([i, pairReqdIndex]);
}
hash[value] = i;
}
return results;
}
const testCases = [
{ input: { array: [4,8,0], target: 8 }, expectedOutput: [[1,0]] },
{ input: { array: [4,-3,80,1,13,9], target: 10 }, expectedOutput: [[1,4], [3,5]] }
];
for (testCase of testCases) {
const actualOutput = getTargetIndexes(testCase.input);
const { expectedOutput } = testCase;
console.log('Test case report', {
'I/P ': testCase.input,
'O/P Expected': expectedOutput,
'O/P Actual': actualOutput,
'Result': JSON.stringify(expectedOutput) === JSON.stringify(actualOutput)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment