Hashmaps

The notes

What is a hashmap?

A data structure that stores key-value pairs for fast lookup (like a dictionary or phone book).

How it works: the core process

Steps

  • 1. Input (key, value): for example Apple = 50 and Orange = 75
  • 2. Hash function, H(key): converts the key into an integer hash code, e.g. H("Apple") gives 731 and H("Orange") gives 492
  • 3. Index calculation: (hash code) % (array length) = index, e.g. 731 % 10 = 1 and 492 % 10 = 2
  • 4. Hash table (array of buckets): items are stored in buckets based on the calculated index

Key concepts

Hash table

  • An array of buckets; each index maps to a bucket

Collision

  • Two different keys hashing to the same index (example: Banana and Grape both land on index 4)

Collision resolution

  • Chaining: store the conflicting keys in a linked list at the same bucket (example: Banana 60 then Grape 90)
  • Open addressing: the other approach named on the card

Features and benefits

  • Fast access: O(1) average-case time for insertions and lookups
  • Efficient lookup: find values quickly by their keys
  • Dynamic resizing: the table can grow as needed based on the load factor
  • Unique keys: each key must be unique (maps to one value)

Data structures deck

  1. 1. Linear vs non-linear
  2. 2. Arrays
  3. 3. Hashmaps
  4. 4. Stacks
  5. 5. Queue
  6. 6. Linked list
  7. 7. Binary tree
  8. 8. BST
  9. 9. Graphs
  10. 10. Heaps

Watch the lesson

Data structures, Lesson 22, from 1:02: Concept Overview