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 LeetCodeBefore 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
- Start an empty hash map
seenofnumber β index. - For each
xat indexi:- Compute
need = target - x. - If
needis inseen, the answer is[seen[need], i]. - Otherwise store
seen[x] = i.
- Compute
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
π» 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.