Two Sum with Hash Map

easyPython

Lesson

Hash Maps for Fast Lookups

When solving problems that involve finding pairs or complements in a dataset, hash maps (dictionaries in Python) are often the key to achieving optimal time complexity.

A hash map stores key-value pairs and provides O(1) average-case lookup time. This means you can check if a value exists in the map almost instantly, regardless of how many items are stored in it. This is much faster than scanning through a list, which takes O(n) time.

The classic pattern for using hash maps in complement-finding problems is:

  1. Iterate through your data once
  2. For each element, calculate what you're looking for (the complement)
  3. Check if that complement already exists in your hash map
  4. If found, you have your answer. If not, store the current element for future lookups

This approach transforms what would be an O(n²) brute force solution (checking every pair) into an O(n) solution by trading space for time. You use extra memory to store the hash map, but you gain significant speed improvements.

The key insight is that instead of asking "what pairs exist?", you ask "for each element, does its complement exist?" This reframing allows you to solve the problem in a single pass through the data.

Example
1def find_complement_pair(numbers, target_sum): 2 """Find if any two numbers in the list add up to target_sum""" 3 seen = {} # Hash map to store numbers we've encountered 4 5 for num in numbers: 6 complement = target_sum - num 7 8 if complement in seen: 9 return True # Found a pair! 10 11 seen[num] = True # Remember this number for later 12 13 return False # No pair found
L2Hash map stores numbers we've seen so far
L5Calculate what number would complete the pair
L7O(1) lookup to check if complement exists
L10Store current number for future complement checks

Key Takeaways

  • •Hash maps provide O(1) lookup time, making them ideal for complement-finding problems
  • •Trading space for time often transforms O(n²) brute force solutions into O(n) optimal solutions
  • •The pattern is: calculate what you need, check if it exists, then store current value for future checks
Loading...