← All problems
#1EasyπŸ”’ Pattern ???

Two Sum

Given an array of numbers and a target, find the indices of two different numbers that add up to the target. Exactly one answer is guaranteed.

Try it on LeetCode
πŸ€” GUESS THE PATTERN+5 XP

Before you peek at the solution: which pattern do you think this one uses?

Hints0/3

Optional. Open them one at a time if you're stuck.

🎬 Walkthrough video

Video coming soon

The video is still being edited. Meanwhile, read the explanation and the code.

πŸ“ Explanation

Intuition

The naive way tries every pair (i, j). That is O(nΒ²) because every number gets compared with every other number.

The key: if the current number is x, we don't need to search for an arbitrary number. We only need to know whether target - x has appeared already. "Have I seen this before?" is exactly what a hash map is for.

Steps

  1. Start an empty hash map seen of number β†’ index.
  2. For each x at index i:
    • Compute need = target - x.
    • If need is in seen, the answer is [seen[need], i].
    • Otherwise store seen[x] = i.

Look the partner up before storing the current number, so one number is never used twice.

Dry run

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

i x need seen before result
0 2 7 {} store 2
1 7 2 {2: 0} found β†’ [0, 1]

⏱️ Complexity

TimeO(n)
SpaceO(n)

πŸ’» Solution code

class Solution:
    def twoSum(self, nums: list[int], target: int) -> list[int]:
        seen = {}  # number -> index
        for i, x in enumerate(nums):
            need = target - x
            if need in seen:
                return [seen[need], i]
            seen[x] = i
        return []

Got it and submitted?

Mark it solved to earn XP and keep your streak alive.