← Algorithm Practice Track

Hash Maps for Constant-Time Lookups

Hash Maps for Constant-Time Lookups

Hash maps (Python dictionaries) are a core tool for making solutions fast.

Why they matter

  • You can check whether a value exists in average O(1) time
  • You can map a value to its index, count, or metadata
  • They often remove one full loop from brute-force solutions

Pattern

  1. Iterate once through the list
  2. Store useful state in a dict
  3. Query the dict while iterating
def two_sum(nums, target):
    seen = {}
    for i, value in enumerate(nums):
        needed = target - value
        if needed in seen:
            return [seen[needed], i]
        seen[value] = i

Common mistakes

  • Updating the dict before checking for the complement
  • Forgetting duplicate values can appear
  • Using dict keys that are not hashable

Practice

Work on:
- Two Sum
- Valid Anagram
- Contains Duplicate

Practice Problems