DEV Community

stuxnat
stuxnat

Posted on

5 2

JavaScript: Two Sum

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) => {

};
Enter fullscreen mode Exit fullscreen mode

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]
    }
};
Enter fullscreen mode Exit fullscreen mode

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!"; 
};
Enter fullscreen mode Exit fullscreen mode

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!";
};
Enter fullscreen mode Exit fullscreen mode

and that's it!

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay