Skip to content

Instantly share code, notes, and snippets.

@clsource
Created Sep 11, 2020
Embed
What would you like to do?
Two Number Sum

Code Challenge: Two Number Sum

Write a function that takes in a non empty array of distinct integers and an integer representing a target sum. If any two numbers in the input array sum up to the target sum, the function should return them in an array. If no two numbers sum up to the target sum, the function should return an empty array. Assume that there will be

Tests Cases

  • Sample input 1: [3,5,-4,8,11,1,-1,6], 10

  • Sample output 1: [-1,11]

  • Sample input 2: [2,-7,4,8,-11],56

  • Sample output 2: []

(() => {
const sum = (values, target) => {
let hare = -1;
let turtle = -1;
for(let hareIndex = 0; hareIndex < values.length; hareIndex++) {
hare = values[hareIndex];
for(let turtleIndex = 0; turtleIndex < values.length; turtleIndex++) {
turtle = values[turtleIndex];
if((turtleIndex !== hareIndex) && turtle + hare === target) {
return [hare, turtle];
}
}
}
return [];
}
// Test Cases
const result1 = sum([3,5,-4,8,11,1,-1,6], 10);
console.assert(JSON.stringify(result1.sort()) == JSON.stringify([-1,11].sort()), result1);
const result2 = sum([2,-7,4,8,-11], 56);
console.assert(JSON.stringify(result2) == JSON.stringify([]), result2);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment