Arrays & Hashing

Hash Map Complement

Two Sum

1Question

Two Sum

EasyLeetCode 1 ↗

You are given an array of numbers nums and a number target. Find two different positions whose numbers add up to target, and return their indices.

Rules

There is exactly one answer. You can not use the same position twice, but two positions can hold the same value (like [3, 3]). You may return the indices in any order.

Examples
Example 1
Input: [2,7,11,15], target = 9
Output: [0,1]

nums[0] + nums[1] = 2 + 7 = 9.

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

2 + 4 = 6. Using 3 twice is not allowed, because it is one position.

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

Two different positions with the same value are fine.

Constraints

2 ≤ nums.length ≤ 104

Up to 10,000 numbers. Checking every pair is about 50 million checks: it passes, but we can do it in O(n).

−109 ≤ nums[i], target ≤ 109

Values can be negative and very large, so we use a hash map, not an array of counts.

Follow-up

Can you find an algorithm faster than O(n²)? Yes: one pass with a hash map.

2Hints

Open one hint at a time. Try to think before you open the next one.

3Pattern

Pattern name

Hash Map Complement

Remember what you passed so that you can find a partner in O(1).

For a pair problem, fixing one number tells you exactly what the other one must be. A hash map stores value → index, so we can jump straight to the partner:

need = target − num; if need in seen: return [seen[need], i]

Every number is looked up once and saved once. The second loop of the brute force disappears.

How to spot this pattern

  • You need two items that combine to a goal (sum, difference, product).
  • Given one item, the other one is fully decided.
  • You must return positions, so sorting would lose them.
  • You are allowed O(n) extra memory.

4Explanation

The big idea: Walk through the array once with a map called seen (value → index). At each number:

Step 1: Look up

Work out need = target − num. If need is in the map, return [seen[need], i].

Step 2: Save

Not found? Save seen[num] = i so a later number can pair with this one.

Why does one pass work? The answer pair has a first and a second position. When we reach the second one, the first is already in the map, so the lookup finds it.

Why check before saving? With [3, 3] and target 6, the first 3 looks for 3 and must not find itself. Saving after the lookup makes sure of that.

5Brute Force

Try every pair of positions.

Idea

A pair is two positions i and j with i before j. So we:

  • Pick every first position i.
  • Try every later position j.
  • If nums[i] + nums[j] == target, return [i, j].
Python
def two_sum_brute(nums, target):
    n = len(nums)

    for i in range(n):
        for j in range(i + 1, n):     # j starts after i, so no position is used twice
            if nums[i] + nums[j] == target:
                return [i, j]

    return []


print(two_sum_brute([2, 7, 11, 15], 9))  # [0, 1]

6Optimal Solution

One pass with a hash map of value → index.

Python
def two_sum(nums, target):
    seen = {}                        # value -> index

    for i, num in enumerate(nums):
        need = target - num          # the partner we are looking for

        if need in seen:             # O(1) lookup
            return [seen[need], i]

        seen[num] = i                # save AFTER the check

    return []


print(two_sum([2, 7, 11, 15], 9))  # [0, 1]

7Time and Space Complexity

Let n be the number of items in the array.

Brute force

Time: O(n²)Space: O(1)

Optimal (hash map)

Time: O(n)Space: O(n)

How big is the difference?

Approximate number of steps:

nBrute force (n²/2)Hash map (n)
104510
1,000499,5001,000
10,000about 50 million10,000

For the biggest input in this problem, the hash map does around 5,000 times less work.

8Visualization

Try:Use 1 to 15 whole numbers (from -99 to 99), separated by commas.
Current Element-
Need-
Answer-
2
7
11
15

Step Analysis

Click "Next" to begin analysis.
Core Logic:
Need = target − num
If need in map: return [map[need], i]
Else: map[num] = i