Two Sum
LeetCode 1 · Easy · solution, intuition & step-by-step walkthrough
Store seen values in a map; look up target − num before inserting num.
This is how I solved Two Sum (LeetCode 1), an easy problem from the Hashing / Anagram pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
For each number, the partner you need is target − num. Instead of searching the rest of the array for it, remember every number you've already passed in a hash map (value → index); then checking whether the partner exists is a single lookup.
Approach
- 1
Walk the array once with index and value.
- 2
Compute remaining = target − num.
- 3
If remaining is already in the map, return its index and the current index.
- 4
Otherwise record num → index and continue.
How I solved it
One-pass hash mapPythonO(n) time · O(n) space
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
mpp = {}
for index, num in enumerate(nums):
remaining = target - num
if remaining in mpp:
last_index = mpp.get(remaining)
return [index,last_index]
mpp[num]=index
return -1Two Sum — FAQ
What is the intuition behind Two Sum?
For each number, the partner you need is target − num. Instead of searching the rest of the array for it, remember every number you've already passed in a hash map (value → index); then checking whether the partner exists is a single lookup.
How do you solve Two Sum (LeetCode 1)?
1. Walk the array once with index and value. 2. Compute remaining = target − num. 3. If remaining is already in the map, return its index and the current index. 4. Otherwise record num → index and continue.
What is the time and space complexity of Two Sum?
Time: O(n). Space: O(n). (Accepted approach: One-pass hash map.)
What are common mistakes in Two Sum?
Check the map before inserting the current number, so an element is never paired with itself. Duplicates like [3,3] work because the first 3 is stored before the second is checked.