DEV Community

loading...

Checking whether there are any two numbers that will sum up to a given number

colerau profile image Cole Rau Updated on ・2 min read

In this article I'll discuss the solution for a common JavaScript interview algorithm:

// In an unsorted array, check whether 
// there are any two numbers that will 
// sum up to a given number. Example:

// sumFinder([6, 4, 3, 2], 9) = true 
// (because 6 + 3 equals 9.)

// sumFinder([6, 4, 3, 2], 2) = false 
// (because nothing in the array plus 
// another number in the array equals 2.) 
Enter fullscreen mode Exit fullscreen mode

JavaScript Implementation

function sumFinder(arr, num) {
  let obj = {}
  let diff

  for (let i = 0; i < arr.length; i++) {
    diff = num - arr[i]

    if (obj[diff]) {
      return true
    } else {
      obj[arr[i]] = true
    }
  }
  return false
}

let sumFinderResult = sumFinder([6, 4, 3, 2], 7)
// returns true

let anotherSumFinderResult = sumFinder([6, 4, 3, 2], 1)
// returns false
Enter fullscreen mode Exit fullscreen mode

Short Explanation of the Solution

If the difference between the function's given target number (the number provided by itself in the arguments list) and an element in the array is equal to another element in the array, return true. Else, return false.

Longer Explanation of the Solution

  • For each element in the array, get the difference between the given number (the number provided by itself in the arguments list) and the current element in the array.
  • Put the current element into an object as a key.
  • If any element in the array (if any key in our object) matches the difference between the given number and the new current element, return true.
  • Else, return false.

An example of the solution using concrete numbers

Let's say sumFinder was called with two parameters: an array of [6, 4, 3, 2], and a given number of 7:

sumFinder([6, 4, 3, 2], 7)
Enter fullscreen mode Exit fullscreen mode

First, according to the above code implementation, an empty object is created, and a diff variable is declared. Then, a for loop is created that loops through each index of the array. The first index points to 6. The line:

diff = num - arr[i]
Enter fullscreen mode Exit fullscreen mode

now translates to:

diff = 7 - 6
// diff is now assigned 1
Enter fullscreen mode Exit fullscreen mode

Since a key of 1 doesn't yet exist in our object, we will insert arr[i], or 6 as a key in our object.

Now on the second loop iteration, our num is 7 (the num never changes). The arr[i] is 4, and the diff is therefore 3. Since 3 is not yet a key in our object, we will add arr[i], or 4 as a key in our object.

On the third loop iteration, our num is 7, the arr[i] is 3, and the diff is therefore 4. This time, 4 is a key in our object, so we return true. We return true because we have successfully figured out that there are two numbers in our array (3 and 4) that will sum up to our given number (7).

Discussion (0)

pic
Editor guide