Two Sum is another question frequently asked during interviews. There are two common ways to approach this problem. One way is considered "brute force" - it uses nested loops with a time complexity of O(nĀ²). The second way is one of the preferred methods, because it has a time complexity of O(n).
The problem asks: given an array of numbers and a target sum, find the sum of two numbers in the array that is equal to the target sum. This is how to solve it:
Step 1. Start with an array of numbers and a target sum
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const sum = 15;
const twoSum = (array, sum) => {
};
Step 2. Write a for-loop to iterate through the array.
const twoSum = (array, sum) => {
const past = []
for(let i = 0; i < array.length; i++){
let curr = array[i]
let needed = sum - array[i]
}
};
Step 3. Write if-statement to search through array of past numbers
const twoSum = (array, sum) => {
const past = []
for(let i = 0; i < array.length; i++){
let curr = array[i]
let needed = sum - array[i]
if(!past.includes(needed)){
past.push(curr)
} else {
return [needed, curr];
}
}
return "Not found!";
};
Step 4. Add counter that will increment by one each run
This will show how many runs it takes to return "Not Found!"
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const sum = 20;
const twoSum = (array, sum) => {
const past = [];
let count = 0;
for (let i = 0; i < array.length; i++) {
let curr = array[i]
let needed = sum - array[i]
if (!past.includes(needed)) {
past.push(curr)
} else {
return [needed, curr];
}
count++;
}
console.log(count)
return "Not found!";
};
and that's it!
Top comments (0)