Skip to content

Instantly share code, notes, and snippets.

@kevinwucodes
Last active September 22, 2021 17:53
Show Gist options
  • Save kevinwucodes/250f35d10ac15b25772af1e02618468d to your computer and use it in GitHub Desktop.
Save kevinwucodes/250f35d10ac15b25772af1e02618468d to your computer and use it in GitHub Desktop.
daily coding problem #1: Given a list of numbers and a number k, return whether any two numbers from the list add up to k

This problem was recently asked by Google.

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.

function isAddedNumberInArray(inputAry, n) {
  return (
    inputAry
      .map((el, index, ary) => {
        //clone array
        const clonedAry = ary.slice()

        //remove the current element
        clonedAry.splice(index, 1)

        if (clonedAry.includes(n - el)) {
          return true
        } else {
          return false
        }
      })
      //if there is at least one true, then the whole thing is true
      .some(el => el == true)
  )
}

console.log(isAddedNumberInArray([10, 15, 3, 7], 17)) //true
console.log(isAddedNumberInArray([10, 15, 3, 7], 19)) //false

//check that the same number isn't used more than once
console.log(isAddedNumberInArray([10, 15, 3, 7], 14)) //false

//rearranged numbers
console.log(isAddedNumberInArray([15, 10, 3, 7], 17)) //true

console.log(isAddedNumberInArray([10, 15, 3, 7], 14)) //false

console.log(isAddedNumberInArray([9, 23, 1, 15, 3, 7], 22)) //true

Bonus: Can you do this in one pass?

//???
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment