Arrays & Strings/Practice/Two Sum

Two Sum - Visual Walkthrough & Python Solution

easyTime: O(n)Space: O(n)

Walk the array once, keeping a hash map of every number you have seen and its index. Before storing the current number, ask the map: have I already seen target minus this number? The moment the answer is yes, you have your pair.

Why it works

A brute-force solution checks every pair of numbers, which is O(n²). The hash map turns the inner loop into a constant-time lookup: instead of searching for a partner, you ask memory directly. One pass, O(n) time, O(n) space for the map.

The problem

Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target. Each input has exactly one solution. You may not use the same element twice.

Hints

  • A brute-force O(n^2) solution checks every pair. Can you do better?
  • Store each number's index in a hash map as you iterate.
  • For each element x, check if (target - x) is already in the map.

Test cases

InputExpected
two_sum([2, 7, 11, 15], 9)[0, 1]
two_sum([3, 2, 4], 6)[1, 2]
two_sum([3, 3], 6)[0, 1]

Reference starter code

def two_sum(nums, target):
    # Your solution here
    pass

# Test
print(two_sum([2, 7, 11, 15], 9))   # [0, 1]
print(two_sum([3, 2, 4], 6))        # [1, 2]
print(two_sum([3, 3], 6))           # [0, 1]

More challenges in this topic

Try it yourself

Solve it in the browser editor with real test cases and instant feedback - free, no signup needed.

Next challenge in this topic: Maximum Subarray
Studying Arrays & Strings but not ready to grind? Get the 30-day plan by email.
One email with the study plan. No spam, unsubscribe anytime.