re: Daily Coding Problem #1 VIEW POST


In JavaScript you could do

function doTheyAddTo(a, k){
    for (const n of a){
        if (a.includes(k-=n))  {
            return true
        return false

    doTheyAddTo( [10, 15, 3, 7], 17)

looks good, but when you use includes is it O(log n) ?



Two problems I can find.

The first is that I don't think you want to do k-=n, rather just k-n. As written, this will only work with pairs with the first number in the array.

Second, you need to limit the includes check to the remainder of the array, or you will fail in cases such as doTheyAddTo([5], 10), because 5 will be considered as a valid addend of itself.

To fix the latter, refactor into a for (let i = 0, n; i < a.length; n = a[i++]) loop to get access to the index, or the much much more readable find, e.g...

function doTheAddTo(a, k){
  a.find((n, i) => {
    // because we're in a closure instead of a loop iteration,
    // we also don't have to worry about prematurely returning false
    // and can instead just return the value of our check
    return a.includes(k-n, i+1)

Note, using find instead of reduce or filter will maintain the short circuit you had.


Your function does not return anything though. Even if you do return the value of the initial find it won't be a Boolean.

whoops. too much REPL, not enough real code. Should be return typeof a.find(...) !== 'undefined'.

Code of Conduct Report abuse