Daily Coding Problem 1

This website sends an email to you with a programming problem, from legitimate interview questions.

I like to use these to get more familiar with a new language, or like doing crossword puzzles, so I’ll post my solutions here. I’ll start with JavaScript but I might change to something else down the track.

Today’s problem:

Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?

My solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const addUpToK = (array, k) => {
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array.length; j++) {
if (i !== j) { // don't check a number against itself
if (array[i] + array[j] === k) {
return true;
}
}
}
}
return false;
}

console.log(addUpToK([10, 15, 3, 7], 17)); // true
console.log(addUpToK([10, 15, 3, 4], 17)); // false

Output:

1
2
3
➜ node addUpToK.js 
true
false