LeetCode Blind75  #1 - Two Sum (Easy)

LeetCode Blind75 #1 - Two Sum (Easy)

Brute Force | HashMap

ยท

1 min read

Table of contents

No heading

No headings in the article.

Problem Statement

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.

Test Cases

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

TC 2
Input: nums = [3,2,4], target = 6
Output: [1,2]

TC 3
Input: nums = [3,3], target = 6
Output: [0,1]

Constraints

2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.

Solutions

#S1 - Brute Force (49ms)

Here, we try to check each and every possible combination through array.

for(int i=0;i<nums.length;i++){
        for(int j=i+1;j<nums.length;j++){
            if(nums[i]+ nums[j]==target){
                    return new int[]{i, j};
            }
        }
    }
    return null;

// Time Complexity : O(n^2)
// Space Complexity : O(1)

#S2 - Using HashMap (1ms)

Here, we use Map data structure to reduce time complexity from polynomial to linear.

HashMap<Integer,Integer> set = new HashMap<Integer,Integer>();         
    for(int i=0;i<nums.length;i++){            
        if(set.containsKey(target-nums[i])){
                return new int[]{set.get(target-nums[i]),i};
        }
        set.put(nums[i], i);        
    }        
    return null;

// Time Complexity : O(n)
// Space Complexity : O(n)
ย