solve the two sum problem
brute force solution
[ nested for loops ]

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

Brute Force algorithm

The Brute Force method involves checking all possible pairs of numbers in the array to determine if any two numbers sum to the target value. While this method is straightforward, it is not the most efficient, especially for large datasets.

Brute force method has a time complexity of O(n2)


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 nested for loops


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


Nested for loops

A nested loop is a loop inside another loop.

A nested for loop consists of an outer for loop and one or more inner for loops

Each time the outer for loop repeats, the control re-enters inside the inner for loop and starts a new execution.

The outer loop iterates through the rows, while the inner loop iterates through the columns.

const rows = [1, 2, 3];

const columns = ["A", "B", "C"];

for (let x = 0; x < rows.length; x++) { → outer loop

for (let y = 0; y < columns.length; y++) { → inner loop

console.log(`row ${rows[x]} : column ${columns[y]}`);

}

}

returns ↴

row 1 : column A

row 1 : column B

row 1 : column C

row 2 : column A

row 2 : column B

row 2 : column C

row 3 : column A

row 3 : column B

row 3 : column C printed to console

Generate a multiplication table.

for (let x = 1; x <= 12; x++) { → outer loop

let row = "";

for (let y = 1; y <= 10; y++) { → inner loop

row += (x * y) + "\t";

}

console.log(row);

}

returns ↴

1  2  3  4  5  6  7  8  9  10

2  4  6  8  10 12 14 16 18 20

3  6  9  12 15 18 21 24 27 30

4  8  12 16 20 24 28 32 36 40

5  10 15 20 25 30 35 40 45 50

6  12 18 24 30 36 42 48 54 60

7  14 21 28 35 42 49 56 63 70

8  16 24 32 40 48 56 64 72 80

9  18 27 36 45 54 63 72 81 90

10 20 30 40 50 60 70 80 90 100

11 22 33 44 55 66 77 88 99 110

12 24 36 48 60 72 84 96 108 120 → printed to console

rows ⇣ outer loop

columns ⇢ inner loop

The outer loop iterates through the rows ⇣ 1 to 12

The inner loop iterates through the columns ⇢ 1 to 10.


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 twoSumBruteForce to check whether any two numbers will sum up to a given number.

function twoSumBruteForce(arr, sum) {}

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

The function uses a nested loop approach to check all possible pairs of numbers within the array.

Get the length of arr

let len = arr.length len

Outer loop: Loop through each element in the array.

for (let x = 0; x < len - 1; x++) {} x = 0

Inner loop: Loop through the elements that come after the current element.

for (let y = x + 1; y < len; y++) {} y = x + 1

Check if the sum of the two elements equals the target sum.

if (arr[x] + arr[y] == sum) {}

If a pair is found that meets the condition, the indices are returned.

return [x, y]

If no valid pair is found, the function returns null.

return null

The function starts with the first number in the array and tries to find if another number in the array will sum up to the target number.

If no other number sums up to the target number, then the second element in the array is tested.

There may be multiple correct combinations where two numbers sum up to a target number.

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.

const arr = [2, 4, 6, 8] array

const num = 12 number to sum up to

arr[x] outer loop

arr[y] y = x + 1 inner loop

len = arr.length

The nested loops test all possible pairs of elements within the array.

The outer loop iterates through each element of the array, except the last one.

for (let x = 0; x < len - 1; x++) outer loop

The inner loop starts from the element immediately following the current element of the outer loop. This ensures that each pair is only checked once and avoids duplicate checks.

for (let y = x + 1; y < len; y++) inner loop

If the sum of the two elements equals the target sum, the function returns their indices.

if (arr[x] + arr[y] == sum) return [x, y]

arr = [2, 4, 6, 8] array with 4 elements

num = 12 number to sum up to

Iteration ↴

0 1st element + 2nd element == num

1 1st element + 3rd element == num

2 1st element + 4th element == num

3 2nd element + 3rd element == num

4 2nd element + 4th element == num

5 3rd element + 4th element == num

Iteration ↴

arr[x] arr[y]

0 2 + 4 == 12 false

1 2 + 6 == 12 false

2 2 + 8 == 12 false

3 4 + 6 == 12 false

4 4 + 8 == 12 true → two numbers found that sum up to 12.

Return indices of the two numbers found and end execution of function.

If no two numbers found that sum up to given number, return null.


Call the function with ↴

twoSumBruteForce(array1, number1);


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

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

const number1 = 12;

function twoSumBruteForce(arr, sum) {

let len = arr.length;

for (let x = 0; x < len - 1; x++) {

for (let y = x + 1; y < len; y++) {

if (arr[x] + arr[y] == sum) {

return [x, y];

}

}

}

return null;

}

call function

twoSumBruteForce(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