Dry run
nums = [3, 8, 2, 11, 7, 15] · target = 9Step 1 of 6
3
08
12
211
37
415
5seen (hash map)value → index
emptyStart with an empty hash map. It will remember every number we've passed and where we saw it.
Pythontime O(n) · space O(n)
1def twoSum(nums, target):
2 seen = {}
3 for i, x in enumerate(nums):
4 need = target - x
5 if need in seen:
6 return [seen[need], i]
7 seen[x] = i
8 return []
Variables
i—
nums[i]—
need—
Problem
Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target.
You may assume each input has exactly one solution, and you may not use the same element twice.
Examples
Input: nums = [2,7,11,15], target = 9Output: [0,1]
nums[0] + nums[1] = 2 + 7 = 9
Input: nums = [3,2,4], target = 6Output: [1,2]
Constraints
- 2 ≤ nums.length ≤ 10⁴
- -10⁹ ≤ nums[i] ≤ 10⁹
- Only one valid answer exists.
Intuition
For each number x we need exactly one partner: target − x. Instead of searching the rest of the array for it, remember every number we have already passed in a hash map. Then 'have I seen my partner?' is a single lookup.
Brute force → Optimal
Brute force
Try every pair with two nested loops and check whether it sums to the target.
Time O(n²)Space O(1)
Optimal
One pass with a hash map from value to index. For each number, look up target − x before storing x.
Time O(n)Space O(n)
Complexity
Time O(n)Space O(n)
Edge cases
- Duplicate values, e.g. [3, 3] with target 6: look up before you store, so the element never pairs with itself.
- Negative numbers and zero: target − x can be negative; the map handles it the same way.
Common mistakes
- Storing x before looking up its partner, which lets an element pair with itself.
- Returning values instead of indices.
জটিলতা
O(n)
সময় — অ্যারেটা একবারই ঘুরি, ম্যাপে খোঁজা O(1)।
O(n)
জায়গা — সবচেয়ে খারাপ ক্ষেত্রে সব সংখ্যা ম্যাপে থাকে।
আগের সমস্যা← Valid Anagramপরের সমস্যাGroup Anagrams →