Imagine you have a huge phone book with millions of names and numbers. You want to find a number quickly by name. Which problem does a hash map solve best?
Think about how long it takes to find a name in a phone book if you check every entry one by one.
A hash map uses a key to jump directly to the value's location, avoiding slow searches through all data.
Consider this C# code using a Dictionary (hash map). What will be printed?
var phoneBook = new Dictionary<string, string>(); phoneBook["Alice"] = "123"; phoneBook["Bob"] = "456"; phoneBook["Alice"] = "789"; Console.WriteLine(phoneBook["Alice"]);
What happens if you add a value with the same key again?
In a hash map, adding a value with an existing key updates the old value.
Look at this C# code snippet. Why does it throw an exception?
var map = new Dictionary<int, string>(); map.Add(1, "One"); map.Add(1, "Uno");
Can a hash map have two identical keys?
Hash maps require unique keys. Adding the same key twice causes an exception.
What will this C# code print?
var map = new Dictionary<string, int>(); map["apple"] = 5; map["banana"] = 3; if (map.TryGetValue("orange", out int value)) { Console.WriteLine(value); } else { Console.WriteLine("Not found"); }
What happens if you look for a key that does not exist?
TryGetValue returns false if the key is missing, so the else block runs.
Choose the best description of the main advantage of a hash map compared to a list or array.
Think about how fast you can find an item by key without scanning all elements.
Hash maps use a hash function to find data quickly, usually in constant time, unlike lists which require scanning.
