Approach
Use a Python dict to map each number to its index. For each element, check if target - num is already in the dict. Python dicts are hash tables with O(1) average lookup.
Complexity Analysis
Key Insight
Tip: In Python,
dictlookups are O(1) average. Theinoperator on a dict checks keys, not values — always usecomplement in seennotcomplement in seen.values().
Python Solution
python# Problem: Two Sum using Dictionary # Language: Python # Difficulty: Easy # Time Complexity: O(n) # Space Complexity: O(n) from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: seen = {} # number -> index for i, num in enumerate(nums): complement = target - num # If complement already seen, return both indices if complement in seen: return [seen[complement], i] seen[num] = i return [] # guaranteed to have a solution