DEV Community


Posted on

Two Sum solved in javascript

Two Sum : Javascript

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.


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

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


 var twoSum = function(nums, target) {
    //hash table
    var hash = {};

    for(let i=0; i<=nums.length; i++){
      //current number
        var currentNumber = nums[i];
        //difference in the target and current number
        var requiredNumber = target - currentNumber;
        // find the difference number from hashTable
        const index2 = hash[requiredNumber];

        // if number found, return index 
        // it will return undefined if not found
        if(index2 != undefined) {
            return [index2, i]
        } else {
           // if not number found, we add the number into the hashTable
            hash[currentNumber] = i;


In detail:

  • Declare a empty hash table
  • Loop through the array
  • Store the current number in a variable
  • Find the difference between the the target number and the current number
  • Search for the difference number from the hash table
  • If number found, return the index of the first number and the search number
  • If not found, add the number into the hash table and continues for loop checking.


Hashmap is the optimal solution as the average search time complexity is O(1)

Runtime Memory
84 ms 35.5 MB

Top comments (5)

bhanuchhabra7 profile image
Bhanu Chhabra

This is O(N) complexity, not O(1)
There is for loop, and regardless of list construct, a non breaking for loop traversal is O(N).

linuxnerd profile image
Abhishek Prakash

I think he meant the time complexity of search operation on a hash table is O(1) and not for the solution.

bhanuchhabra7 profile image
Bhanu Chhabra

Well that is quite confusing. Atleast on my part it is.
People report the solution's complexity with subparts to prove some point.

But just pointing complexity of just 1 sub part and not talking about whole algo/solution is somewhat unusual.

bhanuchhabra7 profile image
Bhanu Chhabra

Also the conclusion doesn't matches with any content in description.

The base of conclusion should be discussed in opening statements.

laith00x profile image

hey, can you please explain why in the return statement (return [index2, i]) you added 'i'? what is the value of i and how did it get the correct value? thanks in advance