Back to Dashboard

Two Sum

Easy

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.

Examples

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]

Approach 1: Brute Force

O(n²)
O(1)

The brute force approach is simple. Loop through each element xx and find if there is another value that equals to targetxtarget - x.

class Solution {
    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 };
                }
            }
        }
        // In case there is no solution, we'll just return null
        return null;
    }
}

Approach 2: One-pass HashMap

O(n)
O(n)

We can use a HashMap to store the complement of the current number required to reach the target.

import java.util.HashMap;
import java.util.Map;

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

Complexity Analysis

  • Time Complexity: O(n)O(n) where n is the number of elements in the array. We traverse the list containing nn elements only once.
  • Space Complexity: O(n)O(n). The extra space required depends on the number of items stored in the hash table.

Status

Solved

Complexity

Time
O(n)
Space
O(n)

Tags

ArrayHashMapBlind-75
View Problem Source