- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Two sum problem in linear time in JavaScript

The problem statement says to execute Two sum problem in linear time in JavaScript. It defines and explores the variety of algorithms that can help us find the least common factors present in mutual by the given source data in JavaScript.

## What is the Two sum problem in JavaScript ?

Two Sum Problem in JavScript equals finding a pair of indices present in the array of numbers given as an input that adds up to the target sum which is also provided as an input by the user.

Given an array of integers and target sum , we will traverse the array of numbers to find out the pair of numbers , there can be one or more pairs of numbers that sums up to the target value given as an input source . Once the pair of numbers are found we can look for their indices to solve the problem statement in whole.

The small catch here is each input value present in an array of numbers can be used once only and you cannot use the same element twice for summing up , where the resultant pairs can be returned in any order.

### Example

The visual example of problem statement looks like :

const arr = [ 2 ,5 ,9 ,7 ,3 , 8 , 1 ]; const targetSum = 10 ;

### Output

[ 0, 5 ] = arr[0] + arr[5] [ 2, 6 ] = arr[2] + arr[6] [ 3, 4 ] = arr[3] + arr[4]

Here we are matching the pair programmatically by scanning the whole array to compare each element present in the array with the other different element present in the array , as no duplicacy or repetitiveness of particular element you have already chosen or selected is not allowed to become one of the member of the pair again , this just violates the rule of two sum problem already mentioned in problem statement.

## Algorithm - Using Loop

**Step 1** : Declare a function with name twoSumProblem that takes in input of array of numbers that will act as a main input source to find the pair of indices to suffice the target sum plus the target sum value which will also be given by the user because the pair of indices to find out is highly depending on the sum value required.

**Step 2** : In the given function , we have used nested loop functionality where the outer loop will pick out the first number in the pair of indices and inner loop will pick up the second value out of pair of indices that will move forward with + 1 value of i loop to track and permute different pair of indices in the dataset domain.

**Step 3 **: The permutation of number of pairs of indices would now be taken to the compare functionality to check if addition of the permuted particular pair suffices to the target sum

**Step 4** : If yes , it will return back the particular indices as the pair of indices of elements which add up equal to the targetSum provided by the user .

### Example

function twoSumProblem ( arr , targetSum ) { for(let i = 0; i<arr.length ; i++ ) { for(let j = i+1 ; j<arr.length ; j++) { if(arr[i] + arr[j] === targetSum) { return [ i ,j ] } } } } const arr = [ 2 ,5 ,9 ,7 ,3 , 8 ,1 ]; const pairOfIndices = twoSumProblem(arr , 10); console.log(pairOfIndices);

### Output

[ 0, 5 ]

## Time and Space Complexity

In the above algorithm and code we have used a nested loop where the outer loop will move forward till the length of the array of numbers resulting in O(n) time complexity and the inner loop also moves forward till the length of the array resulting in O(n) time complexity as well. As the inner loop is dependent on outer loop for its traverse, the multiplication of both individual time complexity results O (n) * O(n) = O(n^2) as its worst case time complexity.

The space complexity is O(1) meaning space complexity is constant as we are not allocating any extra memory to solve the problem .

We can refine the twoSumProblem even more in a good efficient way, scaling down the time complexity in sacrifice to space complexity. Because as the problem statement mentioned, to find Two Sum Problems in linear time .

We will use HashMaps to solve the Two Sum Problem in linear time of time and space complexity in Javascript .

## What is HashMaps in JavaScript ?

HashMaps in JavScript works just like arrays behind the scenes where it maps the label to array indexes or indices using hash function. It is a data structure similar to arrays , hashmaps has hash tables that use key and value pairs where the hashed key refers to the index in the array.

The previously solved algorithm has the biggest drawback of time complexity due to nested loop functionality where hashmaps can traverse and find anything or accessing speed of any value is O(1) time complexity which is the biggest advantage.

## Algorithm

The algorithm will strategize to loop the array and traverse each element present in the array for once only and some memory helping must be there to store the indices you get in half way through while targeting the targetSum value. The memory helper here is hashmap whose extra memory allocation discards the second nested loop we used in adobe algorithm and lets problem statements be solved in linear time.

**Step 1 **: Declare a function with name newTwoSumProblem that takes in the array of numbers and targetSum you want to find a pair of indices for.

**Step 2 **: Declare a new hashMap initialize with empty value.

**Step 3** : Traverse the length of the array with the for loop till the length of an array keeping in mind as if there is any other number that can add up to the currentValue of the number to get the target sum achieved.

**Step 4 **: Declare and assign a new variable as an extra memory as mentioned above called as currentValue that will take in present value of i at each iteration of for loop

**Step 5 **: Find the next value of a pair of indices in respect to the current value such that the new value will be calculated on the basis of how much value is left to be needed to achieve target sum using hash function of targetSum - currentValue.

**Step 6** : You look for the pair of indices using hash map function where the current value is stored in key and value pair pattern where the key is the actual value itself and value is the particular indices for that value only.

**Step 7** : If the pair for current value is not found in hashmap and it equals undefined , the hashmap will again start looking for its complementary pair of indices with next value of i to proceed for the other array of numbers and repeat the same task until you find the pair of indices that suffices the target sum.

### Example

function newTwoSumProblem (arr, targetSum) { let hashMap = {}; for(let i = 0; i < arr.length; i++) { const currentValue = arr[i]; if(hashMap[targetSum - currentValue] !== undefined) { return [hashMap[targetSum - currentValue], i]; } hashMap[currentValue] = i; } return []; } const arr = [ 2 ,7 , 11, 15 ]; const pairOfIndices = newTwoSumProblem(arr , 9); console.log(pairOfIndices);

Later we can also call the function using the above main code and the output in console would be :

### Output

[0 , 1 ]

The following code is the efficient and optimized forward code one can think of while looking at the problem statement attained to the better quality of space and time making it more efficient and high quality.

In the above code we have declared a function taking in the array input . Then we go step by step , following first to focus on the prime line of problem statement that says to find any other number in the array of numbers which can add to the current number to equal the target sum value.

And in this way we can start with loop that goes initially to index 0 and try to find the other number value which is obtained using targetSum-currentValue by looking up into the hashtable , if it does not find the current value is stored in hashmap with key and value pair structure and for loop is taken forward to the index value 1 and the same process repeats until it finds the complementary pair of indices sufficing target sum.

## Time and Space Complexity

This is an efficient algorithm that uses hashmap now and takes time complexity of O(n) and space complexity of O(n) as well. Hence it solves the problem statement in linear time.

## Conclusion

This is how we can solve the above problem statement thinking logically and efficiently in the context of coding taking code from nested loops to hashmap functionality which gives us immense power to traverse and perform operations using it in constant time of time and space complexity .

To Continue Learning Please Login

Login with Google