DEV Community

Norris Chebl
Norris Chebl

Posted on

4

Two Sum Algorithm - JavaScript Tutorial/Solution

The Problem

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Enter fullscreen mode Exit fullscreen mode

Basic Solution

The brute force way of solving this would be looping through the array twice and adding up one number from each array to see if it equals the target. This is what it that looks like:

let twoSum = (nums, target) => {
    for(var i = 0; i < nums.length; i++) {
        for(var j = i + 1; j < nums.length; j++) {
            if(nums[i] + nums[j] == target) {
                return [i,j]
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

This is inefficient simply because we have to do double the amount of work when looping through the same array twice. Although this will always work, as the array gets larger, the execution gets exponentially slower.

So let's take a look at how to go through this array only once.

Efficient Solution

First off, we need a way to keep track of all of the numbers we've already looked at as well as what numbers we need. We're going to do this by using a prevValues object to store our values which allows us to look at our numbers instantly without having to loop through the array again to see if the number exists. Take a look:

let twoSum = (nums, target) => {
// Create object to store values
  const previousValues = {}
  for (let i = 0; i < nums.length; i++) {
    const currentValue = nums[i]
    const neededValue = target - currentValue
// Store needed value as a key in the object
    const index2 = previousValues[neededValue]
// Check if we have an index that is equal to our needed value 
    if (index2 != null) {
      return [index2, i]
    } else {
// Store index for current value
      previousValues[currentValue] = i
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

PulumiUP 2025 image

PulumiUP 2025: Cloud Innovation Starts Here

Get inspired by experts at PulumiUP. Discover the latest in platform engineering, IaC, and DevOps. Keynote, demos, panel, and Q&A with Pulumi engineers.

Register Now

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay