solve the two sum problem
hash map solution
[ Map | has | get | set | for loop ]

Solve the two sum problem

Check whether any two numbers will sum up to a given number

Write a function that takes an array of numbers and a target number and identifies two distinct indices in the array such that the values at those indices add up to the target sum. If such a pair exists, the function returns their indices; otherwise, it returns null.


Example ...

Enter an array of numbers and a target number ...

[2, 4, 6, 8] array

12 target number

The function will return the array [1, 3]

The values represent the indices of the two numbers, 4 and 8, that sum up to the target number 12.

4 + 8 = 12

Hash Map algorithm

A HashMap (Map) is a data structure that stores key/value pairs. It allows for efficient retrieval, insertion, and deletion of elements by using a hash function to compute an index into an array where values are stored.

The Hash Map method stores previously encountered numbers and their indices, the algorithm minimizes the need for redundant calculations, thereby enhancing performance.

Hash Map method has a time complexity to O(n)


Arrays are used to store multiple values in a single variable.

Each value is called an element, and each element has a numeric position in the array, known as its index.

Arrays are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on.

Arrays can contain any data type, including numbers, strings, and objects.

const arr1 = [2, 4, 6]; array

arr1[0]; element at index 0 → 2

arr1[1]; element at index 1 → 4

arr1[2]; element at index 2 → 6

arr1[3]; element at index 3 → undefined index not found


Numbers are used to represent both integer and floating-point values.

Numbers are most commonly expressed in literal forms like 255 or 3.14159 ↴

let num1 = 5; → number

let num2 = 2.5; → number

let num3 = num1 + num2;

console.log(num3); returns ↴

7.5 → number


Check whether any two numbers will sum up to a given number using ↴

Map is a collection of key/value pairs.

has() method → returns a boolean indicating whether an element with the specified key exists in this Map or not.

get() method → gets the value associated with the specified key in a Map.

set() method → allows elements to be added to a Map.

for loop → executes a block of code a number of times.


Map is a collection of key/value pairs that can use any data type as a key and can maintain the order of its entries.

Maps have elements of both Arrays (an ordered collection) and Objects (a unique key/value pair collection).

The size and order of entries is preserved like an Array, the entries themselves are key/value pairs like an Object and can be of any data type.

Maps can be initialized with the new Map() syntax.

const map = new Map(); empty map

set() method allows elements to be added to a Map.

The first argument will be the key, and the second argument will be the value.

const map = new Map();

map.set("A", 1);

map.set("B", 2);

map.set("C", 3); returns ↴

Map(3) {"A" => 1, "B" => 2, "C" => 3}

Map uses the => syntax to signify key/value pairs as key => value

get() method gets the value associated with the specified key

map.get("A"); 1

map.get("B"); 2

map.get("C"); 3

map.get("D"); undefined

has() method returns a boolean indicating whether an element with the specified key exists in this map or not.

map.has("A"); → returns boolean ↴

true

map.has("E"); → returns boolean ↴

false


for loop repeatedly executes a block of code until a specified condition evaluates to false.

The loop runs a block of code a set number of times, defined by an initialization, a condition, and an increment.

for (let x = 0; x < 4; x++) {

console.log(x);

}

Loop variable x is initialized to 0

Condition x < 4 is checked before each iteration.

The loop will continue to run as long as x is less than 4

The loop repeatedly executes a block of code 4 times, from 0 to 3

For each iteration of the loop, the current value of x is printed to the console.

After each iteration, x is incremented by 1 x++

When x reaches 4 the condition evaluates to false, terminating the loop.

0

1

2

3 → printed to console


Initialize an array to check if any two elements will sum up to a given number.

const array1 = [2, 4, 6, 8]; → user input

Initialize a variable to hold the target sum to check against.

const number1 = 12; → user input


Define a function twoSumHashMap to check whether any two numbers will sum up to a given number.

function twoSumHashMap(nums, target) {}

The function takes an array nums and a number target as input and returns the indices any two numbers in the array sum up to the given number, otherwise returns null.

Create a new Map to store numbers as keys and their corresponding indices as values.

const numMap = new Map() numMap

Iterate through the array of numbers.

for (let x = 0; x < nums.length; x++) {}

The complement is calculated by subtracting the current number from the target.

This value represents the number we need to find in the array to achieve the target sum.

const complement = target - nums[x] complement

Check if the complement exists in the map.

if (numMap.has(complement)) {}

If the complement is found, the function returns an array containing the index of the complement and the current index x

return [numMap.get(complement), x]

If not found, add the current number and its index to the map.

numMap.set(nums[x], x)

If the loop completes without finding a pair, the function returns null, indicating that no such pair exists.

return null

If the function returns an array then two numbers have been found that sum up to a given number

If the function returns null then two numbers were not found that sum up to a given number


Check whether any two numbers will sum up to a given number.

Calculate the complement of the current number.

const nums = [2, 4, 6, 8] → array

const target = 12 → number to sum up to

for (let x = 0; x < nums.length; x++) {

const complement = target - nums[x]

console.log(complement);

} returns ↴

10

8

6

4 printed to console

The compliment represents the number we need to find in the array to achieve the target sum.

Calculate the complement of the current number.

Iteration ↴

0 target - nums[0] 12 - 2 = 10

1 target - nums[1] 12 - 4 = 8

2 target - nums[2] 12 - 6 = 6

3 target - nums[3] 12 - 8 = 4

Check if the complement exists in the map.

if (numMap.has(complement))

If found, return the indices of the complement and the current number.

return [numMap.get(complement), x]

If the complement is not found, the current number and its index are added to numMap.

numMap.set(nums[x], x)

For example ...

{2 => 0}

compliment is 2 and its index at 0

comp → compliment

curr num → current number

numMap → Map

Iteration ↴

x comp curr num numMap

0 10 2 {2 => 0} added to numMap

1 8 4 {2 => 0, 4 => 1} added to numMap

2 6 6 {2 => 0, 4 => 1, 6 => 2} added to numMap

3 4 8 4 compliment found in numMap

4 compliment found in numMap at index → 1

x current index 3

If the complement is found, the function returns an array containing the index of the complement and the current index x

The function returns the array [1, 3]


Call the function with ↴

twoSumHashMap(array1, number1);


Check whether any two numbers will sum up to a given number.

const array1 = [2, 4, 6, 8];

const number1 = 12;

function twoSumHashMap(nums, target) {

const numMap = new Map();

for (let x = 0; x < nums.length; x++) {

const complement = target - nums[x];

if (numMap.has(complement)) {

return [numMap.get(complement), x];

}

numMap.set(nums[x], x);

}

return null;

}

call function

twoSumHashMap(array1, number1); returns ↴

[1, 3] indices of the two numbers that sum up to target number

4 + 8 = 12

Solve the two sum problem

Check whether any two numbers will sum up to a given number

Enter number to sum up to