Two Sum - Leetcode#1

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

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

You can return the answer in any order.

Examples:

1
2
3
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
1
2
Input: nums = [3,2,4], target = 6
Output: [1,2]
1
2
Input: nums = [3,3], target = 6
Output: [0,1]

Constraints:

1
2
3
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109

Only one valid answer exists.


Solution

1. Brute force Using nested for loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var twoSum = function(nums, target) {
    const n = nums.length;
    let out = [];
    
    for(let i=0; i<n-1; i++) {
        for(let j=i+1; j<n; j++) {
            if(nums[i] + nums[j] === target) {
                out.push(i);
                out.push(j);
            }
        }
    }
    return out;
};

time complexity: O(n^2)

space complexity: O(1)


More optimised approach

2. Using hashmap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var twoSum = function(nums, target) {
    const n = nums.length;
    let out = [];
    let obj = {};
    
    for(let i=0; i<n; i++) {
        const diff = target - nums[i];
            
        if(obj[diff] || obj[diff] === 0) {
            out.push(i);
            out.push(obj[diff]);
            break;
        } else {
            obj[nums[i]] = i;
        }
    }
    return out;
};

time complexity: O(n)

space complexity: O(n)