This problem follows the Hash Map Lookup pattern, commonly found in the Arrays & Hashing category. Recognizing this pattern is key to solving it efficiently in an interview setting.
Store complements in a hash map. For each num, check if target - num exists.
Instead of searching for a pair, search for the complement of each number — this turns an O(n²) nested loop into a single O(n) pass.
map = {}
for i, num in enumerate(nums):
complement = target - num
if complement in map:
return [map[complement], i]
map[num] = iPractice Two Sum and similar Arrays & Hashing problems with flashcards. Build pattern recognition through active recall.
Practice this problem