Skip to main content

Two Sum


Two Sum: 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.

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

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

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

Constraints:
  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
  • Only one valid answer exists.

Try this Problem on your own or check similar problems:

  1. Subarray Sum Equals K
  2. Two Sum II - Input Array Is Sorted
  3. 3Sum
  4. 4Sum
Solution:
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; ++i){
if (map.containsKey(target - nums[i])){
return new int[]{map.get(target - nums[i]), i};
}
map.put(nums[i], i);
}
return new int[]{0,0};
}

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

Explanation:

It's trivial to write O(n^2) solution by checking if sum of any pair in input array sums up to the target, but to reduce time complexity we allocate a helper hashmap that enables us O(1) (amortized) get operation. Each iteration we check if there is an element already in hashmap that together with current element adds up to the target (we do that by subtracting current element from the target map.containsKey(target - nums[i])). If not, we just store the current element in the hasmap hoping we will find its pair in the rest of array (by problem statement we will, since there is a guarantee exactly one solution exists). Notice that we got a unsorted input array, you could make a statement that if array was sorted you would use two pointers approach, where you would place one pointer at the start of sorted array and the other one in the end. If their sum is equal to target you would just return the indices of those two elements, otherwise we would move the start to the right if the sum is less than target or move the right pointer to the left if the sum is larger than target. You can check Squares of a Sorted Array solution to see this approach in action.