The task:

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?

const lst = [14, 10, 3, 7, 0];
const k = 14;

My solution 1:

const addUpTo = (lst, k) => lst.some((x, i) => !isNaN(lst.find((y, j) => i !== j && y === k - x)));

console.log(addUpTo(lst, k));

My solution 2:

const addUpTo2 = (lst, k) => lst.some((x, i) => {
  const find = k - x;
  return !isNaN(lst.slice(i + 1).find(y => y === find));

console.log(addUpTo2(lst, k));
  • 1
    \$\begingroup\$ This question is self-contained. How does this question "lack context"? What is incomplete about this question? \$\endgroup\$ – thadeuszlay Apr 13 '19 at 13:07

These solutions have quadratic runtime. You can store counts (in an object) and check the object for k-x, or sort the array, check values up to k/2 and binary search for k-x. The second approach is asymptotically slower but constant storage.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.