Imagine you want to store and quickly find phone numbers by names. You have two options: a list of pairs (name, number) or a hash map. Why is a hash map better for this?
Think about how many steps it takes to find a name in a list versus a hash map.
A hash map uses a special function to jump directly to the location of the data, so it usually finds it very fast (constant time). A list must check each item until it finds the right one, which takes longer as the list grows.
Consider a hash map that stores integer keys and values. We insert keys 10, 20, and 30 with values 100, 200, and 300 respectively. What is the state of the hash map after these insertions?
hash_map_insert(10, 100); hash_map_insert(20, 200); hash_map_insert(30, 300); print_hash_map();
Keys and values are stored as pairs. The order may vary but all pairs should be present.
After inserting keys 10, 20, and 30 with their values, the hash map contains these pairs. The keys map to their respective values.
Given the code below, why does looking up key 15 return 'not found' even though it was inserted?
hash_map_insert(15, 150); value = hash_map_lookup(15); if (value == NULL) { printf("not found\n"); } else { printf("%d\n", value); }
Think about what happens if two keys hash to the same place.
If the hash function causes two keys to go to the same spot and collisions are not handled, the second key can overwrite or be lost, causing lookup to fail.
You need to store user IDs and their scores in a game. You want to quickly update scores and find a user's score. Which data structure is best and why?
Think about how you find data by a unique key quickly.
A hash map is best for fast lookup and update by key because it uses hashing to jump directly to the data location.
Explain the main problem a hash map solves that arrays and lists struggle with when storing key-value pairs.
Think about how fast you can find a value by key in each data structure.
Arrays and lists require checking each element to find a key, which takes longer as data grows. Hash maps use a hash function to jump directly to the data, making lookup much faster.
