# Two Sum

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.

Example:

``````Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].``````

## Analysis

Input:

``````[3,3]
6``````

Expected:

``[0,1]``

Wrong:

``[1,1]``

## Solution

One Pass HashMap - O(n) time, O(n) space (3ms, 99.76%)

``````class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
int num = nums[i];
if(map.containsKey(target - num)) {
return new int[] {map.get(target - num), i};
}
map.put(num, i);
}
return new int[]{1,1};
}
}``````

Brute Force - Two Loops - O(n^2) time, O(1) space

``````public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}``````

Two Pass Hash Table: O(n) time, O(n) space - (8ms 56.82%)

Beware that the complement must not be `nums[i]` itself!

``````public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}``````

Last updated