Skip to content

Instantly share code, notes, and snippets.

@jaboulos
Last active March 12, 2019 04:00
Show Gist options
  • Save jaboulos/33785b7987793d3796d476bd2b5ff497 to your computer and use it in GitHub Desktop.
Save jaboulos/33785b7987793d3796d476bd2b5ff497 to your computer and use it in GitHub Desktop.
Integer pairs - toy problem
// integerPairs
// Design an algorithm to find all pairs of integers within an array which sum to a specified value.
// Input: array
// Output: array of pairs
// Time complexity: O(n)
// Space complexity: no constraints
// Example:
// Input: [3, 2, 8, 9, -1, 4, 5, 12, 1], 7
// Output: [ [ 3, 4 ], [ 2, 5 ], [ 8, -1 ] ] (order of pairs does not matter)
var input = [3, 2, 8, 9, -1, 4, 5, 12, 1] //7
var target = 7;
function integerPairs(input, target) {
// make one array to hold all arrays
var largeArray = [];
// loop through the input array
for(var i = 0; i < input.length; i++) {
// crate a variable array to hold number pairs that sum to the target
var smallArray = [];
// make a 2nd loop to check the number next to the starting input value
for(var j = i+1; j < input.length; j++) {
// check to see if the two values sum to the target value
if(input[i] + input[j] === target) {
// if yes, push both values into the small array
smallArray.push(input[i], input[j])
// push the array of the pairs into a large array
largeArray.push(smallArray);
}
}
}
// return the large array
return largeArray;
}
integerPairs(input, target);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment