beginnerdata-structures

Hash Maps

Hash Maps

A hash map (also called a hash table or dictionary) is a data structure that maps keys to values using a hash function. It provides O(1) average-case time for insertions, deletions, and lookups — making it one of the most widely used data structures in programming. Python's dict, JavaScript's Object/Map, and Java's HashMap are all hash maps under the hood.

How It Works

  1. Hash the key: Apply a hash function to convert the key into an integer
  2. Compute the index: Use modulo to map the hash to a valid array index: index = hash(key) % table_size
  3. Store the value: Place the key-value pair at the computed index
  4. Handle collisions: When two keys map to the same index, use a collision resolution strategy

The Hash Function

A good hash function has these properties:

  • Deterministic: Same key always produces the same hash
  • Uniform distribution: Spreads keys evenly across the table
  • Fast to compute: O(1) time for any key

Example: For string keys, a common approach multiplies each character's ASCII value by powers of a prime number.

Collision Resolution

When two different keys hash to the same index, we have a collision. Two main strategies:

Chaining (Separate Chaining)

Each table slot holds a linked list (or array) of all key-value pairs that hash to that index.

Open Addressing (Linear Probing)

When a collision occurs, probe the next available slot in the table.

Step-by-Step Example

Insert keys with table size 7:

insert("cat", 1): hash("cat") % 7 = 3 → table[3] = ("cat", 1)
insert("dog", 2): hash("dog") % 7 = 5 → table[5] = ("dog", 2)
insert("rat", 3): hash("rat") % 7 = 3 → collision! Chain at table[3]
lookup("cat"):    hash("cat") % 7 = 3 → search chain → found ("cat", 1)
delete("cat"):    hash("cat") % 7 = 3 → search chain → remove ("cat", 1)

Code Snippet

class HashMap:
    """Hash map with separate chaining for collision resolution."""

    def __init__(self, capacity: int = 16):
        self._capacity = capacity
        self._size = 0
        self._buckets = [[] for _ in range(capacity)]
        self._load_factor_threshold = 0.75

    def _hash(self, key: str) -> int:
        """Compute hash index for a string key."""
        hash_value = 0
        for char in key:
            hash_value = hash_value * 31 + ord(char)
        return hash_value % self._capacity

    def put(self, key: str, value) -> None:
        """Insert or update a key-value pair."""
        index = self._hash(key)
        bucket = self._buckets[index]

        # Update existing key
        for i, (existing_key, _) in enumerate(bucket):
            if existing_key == key:
                bucket[i] = (key, value)
                return

        # Insert new key
        bucket.append((key, value))
        self._size += 1

        # Resize if load factor exceeded
        if self._size / self._capacity > self._load_factor_threshold:
            self._resize()

    def get(self, key: str):
        """Retrieve value by key. Returns None if not found."""
        index = self._hash(key)
        bucket = self._buckets[index]

        for existing_key, value in bucket:
            if existing_key == key:
                return value
        return None

    def remove(self, key: str) -> bool:
        """Remove a key-value pair. Returns True if found."""
        index = self._hash(key)
        bucket = self._buckets[index]

        for i, (existing_key, _) in enumerate(bucket):
            if existing_key == key:
                bucket.pop(i)
                self._size -= 1
                return True
        return False

    def _resize(self) -> None:
        """Double capacity and rehash all entries."""
        old_buckets = self._buckets
        self._capacity *= 2
        self._buckets = [[] for _ in range(self._capacity)]
        self._size = 0

        for bucket in old_buckets:
            for key, value in bucket:
                self.put(key, value)

Complexity Analysis

Time Complexity: O(1) average, O(n) worst case

  • Average case: With a good hash function and load factor below 0.75, most operations access one bucket with one or two entries — effectively O(1).
  • Worst case: If all keys hash to the same bucket, every operation must traverse the entire chain — O(n). This is extremely rare with a proper hash function.

Space Complexity: O(n)

The hash map stores n key-value pairs plus the table array. With resizing, the table capacity is always within a constant factor of n.

Load Factor and Resizing

The load factor = n / capacity. When it exceeds a threshold (typically 0.75):

  • Double the table capacity
  • Rehash all existing entries into the new table

This keeps chains short and maintains O(1) average performance. Resizing itself is O(n), but it happens infrequently enough that the amortized cost per operation remains O(1).

When to Use Hash Maps

  • Frequency counting: Count occurrences of elements in O(n) time.
  • Caching/Memoization: Store computed results for fast retrieval.
  • Deduplication: Track seen elements to detect duplicates.
  • Indexing: Build lookup tables mapping IDs to records.
  • Two-sum style problems: Check for complement values in O(1).
  • Symbol tables: Compilers use hash maps for variable/function name resolution.

When to Avoid Hash Maps

  • Ordered traversal needed: Hash maps don't maintain insertion or sorted order. Use a balanced BST or sorted array instead.
  • Memory constrained: The table array and linked list pointers add overhead beyond the raw data.
  • Small fixed datasets: For very few keys, a simple array or linear scan may be simpler and faster.

Key Properties

PropertyValue
Average lookupO(1)
Worst-case lookupO(n)
OrderedNo (unordered)
Duplicate keysNo (values overwritten)
Null keysImplementation-dependent