Two Sum

Easy
The course
Array, Hash Map Complement Lookup, One-Pass Hash Map
1

Understand

Before writing anything, get clear on what is being asked.

Think of it like this

Imagine a room of people, each wearing a number, and you need to find two whose numbers add to 9. The slow way is to walk every person up to every other person. The fast way: as you meet each person, you already know who you need — if you are shaking hands with 2, you need 7 — so you just ask whether you have met a 7 yet. Your memory of who you have met is the hash map.

Almost every efficient array solution comes from the same move: replace "search the array again" with "remember what I have already seen". That trade — a little memory to remove a whole loop — is the single most reusable idea in this course.

You are given an array of whole numbers and a target value. Exactly one pair of positions in the array adds up to that target. Return those two positions.

You may assume there is exactly one valid answer, and you may not use the same position twice. The order of the two positions you return does not matter.

Example 1

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

Answer [0, 1]

nums[0] + nums[1] = 2 + 7 = 9, so the answer is positions 0 and 1.

Example 2

Given nums = [3, 2, 4], target = 6

Answer [1, 2]

The answer is not always the first two values — here it is 2 + 4.

Example 3

Given nums = [3, 3], target = 6

Answer [0, 1]

The same value can appear twice; they are different positions.

What you can rely on

  • The array holds between 2 and 10,000 numbers
  • Each number is between -1,000,000,000 and 1,000,000,000
  • Exactly one valid pair exists
2

Get it working

Any working answer counts. Slow is fine — correct first, fast later.

The editor on the right already has the function signature filled in for you. Write your answer inside it and press Run — that checks your code against the examples above only, so you can experiment freely.

Run your code to tick this step off.

Stuck? Take one hint at a time

Each one nudges you a little further. There is no reveal-the-answer button — working it out is the part that actually teaches you.

3

Make it fast

Now find out why the obvious answer will not survive a big input.

Start with the obvious: check every pair

O(n²) time · O(1) space

Write the version you would explain to a friend first. Take every position, pair it with every later position, and check whether the two add up to the target. It is correct, and correct is where you always start.

Brute force — two nested loops
class Solution:
    def twoSum(self, nums, target):
        for i in range(len(nums)):
            for j in range(i + 1, len(nums)):
                if nums[i] + nums[j] == target:
                    return [i, j]
        return []

The constraint says the array can hold 10,000 numbers. That is 50 million pairs — slow but survivable. Push it to 100,000 and it becomes 5 billion, and the same code times out. This is exactly what week 2 means by letting the constraints tell you the complexity you need.

One pass with a hash map

O(n) time · O(n) space

The inner loop only ever asks one question: "is the value target − nums[i] somewhere in this array?" A hash map answers that in constant time, so the inner loop disappears entirely.

Walk the array once. At each value, first check whether its complement is already in the map — if it is, you have the pair. Otherwise record the current value and its position, and move on.

Tracing nums = [2, 7, 11, 15], target = 9
inums[i]need (target − nums[i])seen so faraction
027{}not found → record 2 → 0
172{2: 0}found 2 at 0 → return [0, 1]

Checking before inserting is what makes the "same value twice" case work. On [3, 3] with target 6, the first 3 is recorded, then the second 3 looks for a 3 and finds the first one — two different positions, exactly as required.

ApproachTimeSpace
Brute force (nested loops)O(n²)O(1)
One-pass hash mapEach value is visited once; each map operation is O(1) on average.O(n)O(n)

Why do we check the map for the complement BEFORE inserting the current value?

4

Own it

Submit against every test, then check you can explain why it works.

Press Submit to run every test, including the hidden ones.