Bravo
Bravo

Reputation: 121

how to improve : Two Sum Given an array of integers, return indices of the two numbers... using angular

I was looking for better solution to the leetcode problem mentioned below.

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

let twoSum = function(nums, target) {
    for(let i = 0; i < nums.length; i++){
        for(let j = i+1; j < nums.length; j++){
            if(nums[i] + nums[j] == target){
                return [i, j]
            }
        }
    }
};

Upvotes: 1

Views: 1006

Answers (1)

Abito Prakash
Abito Prakash

Reputation: 4770

We can use a Map to do this in O(n) time. Iterate over each number (let say num) in the array and check if target - num is already present in the map. If it is present, it means that in previous iterations we have already seen a number which when added to current num returns the target. And in each iteration we are putting the current num as key and it's index as value in the Map.

const twoSum = (nums, target) => {
    const map = new Map();

    for (let i = 0; i < nums.length; i++) {
        const diff = target - nums[i];
        if (map.has(diff)) {
            return [map.get(diff), i];
        }
        map.set(nums[i], i);
    }

    return [];
};
console.log(twoSum([1, 2, 3, 4, 5], 9));

Upvotes: 2

Related Questions