📖 Scenario: Imagine you want to build a simple phone book app that stores names and phone numbers. To do this efficiently, you will create your own version of a HashMap in Go. This will help you understand how data is stored and retrieved quickly.
🎯 Goal: Build a basic HashMap in Go that can store key-value pairs (string keys and string values), add new entries, and retrieve values by key.
📋 What You'll Learn
Create a HashMap struct with buckets
Implement a simple hash function for string keys
Add a method to insert key-value pairs
Add a method to retrieve values by key
Print the stored values to verify correctness
💡 Why This Matters
🌍 Real World
HashMaps are used in many applications like phone books, caches, and databases to store and quickly retrieve data by keys.
💼 Career
Understanding how hash maps work is essential for software developers, especially when optimizing data storage and retrieval in applications.
Progress0 / 4 steps
1
Create the HashMap data structure
Create a struct called HashMap with a field buckets which is a slice of slices of key-value pairs. Define a struct called KeyValue with key and value fields, both of type string. Initialize buckets with 5 empty slices.
DSA Go
Hint
Use make([][]KeyValue, 5) to create 5 empty buckets.
2
Add a hash function
Add a method hash to HashMap that takes a key string and returns an int. The method should sum the ASCII values of all characters in the key and return the sum modulo the number of buckets (5).
DSA Go
Hint
Loop over each character in the key and add its integer value to sum.
3
Add method to insert key-value pairs
Add a method Put to HashMap that takes key string and value string. Use the hash method to find the bucket index. Append a new KeyValue with the given key and value to the bucket at that index.
DSA Go
Hint
Use append to add the new key-value pair to the correct bucket.
4
Add method to get value by key and print results
Add a method Get to HashMap that takes key string and returns string and bool. Use the hash method to find the bucket index. Search the bucket for the key and return the value and true if found. Otherwise, return empty string and false. In main, create a HashMap, add these pairs using Put: "Alice" : "1234", "Bob" : "5678", "Charlie" : "91011". Then print the results of Get("Alice"), Get("Bob"), and Get("Eve").
DSA Go
Hint
Loop through the bucket to find the key. Print the results exactly as shown.
Practice
(1/5)
1. What is the main purpose of a HashMap in data structures?
easy
A. To store key-value pairs for fast data retrieval
B. To store elements in a sorted order
C. To perform mathematical calculations
D. To store data sequentially like an array
Solution
Step 1: Understand the role of HashMap
A HashMap stores data as key-value pairs, allowing quick access to values using keys.
Step 2: Compare with other data structures
Unlike arrays or lists, HashMaps do not store data sequentially or sorted but focus on fast lookup.
Final Answer:
To store key-value pairs for fast data retrieval -> Option A
Quick Check:
HashMap = key-value fast access [OK]
Hint: HashMap = key-value pairs for quick lookup [OK]
Common Mistakes:
Confusing HashMap with arrays or lists
Thinking HashMap stores data in order
Assuming HashMap is for mathematical operations
2. Which of the following is the correct way to declare a HashMap in Go?
easy
A. var m = make(map[string]int)
B. var m map[string]int = map[string]int
C. var m = map[string]int()
D. var m map[string]int
Solution
Step 1: Understand Go map declaration
In Go, maps are created using make function: make(map[keyType]valueType).
Step 2: Check each option
A declares a nil map which cannot be used for assignments. B has invalid syntax (cannot assign type as value). C has incorrect syntax (cannot call map type as function). D uses make correctly.
Final Answer:
var m = make(map[string]int) -> Option A
Quick Check:
Use make() to create maps in Go [OK]
Hint: Use make(map[key]value) to create HashMap in Go [OK]
Common Mistakes:
Declaring without initializing (nil map)
Using map type without literal or make
Trying to call map as a function
3. What will be the output of the following Go code snippet implementing a simple HashMap?
Initially, "apple" is set to 5, then updated to 7, so the last value is 7.
Step 2: Print the value for key "apple"
Printing m["apple"] outputs the updated value 7.
Final Answer:
7 -> Option D
Quick Check:
Last assigned value for key is returned [OK]
Hint: Last value assigned to key is stored [OK]
Common Mistakes:
Assuming first value remains after update
Confusing zero value with stored value
Expecting compilation error due to reassignment
4. Identify the error in this Go code implementing a HashMap:
package main
import "fmt"
func main() {
var m map[string]int
m["key"] = 10
fmt.Println(m["key"])
}
medium
A. Key type is incorrect
B. Map is not initialized before use
C. Value type is incorrect
D. Print statement syntax error
Solution
Step 1: Check map initialization
The map variable m is declared but not initialized with make(), so it is nil.
Step 2: Understand assignment to nil map
Assigning to a nil map causes runtime panic because map is not ready to store data.
Final Answer:
Map is not initialized before use -> Option B
Quick Check:
Maps must be initialized with make() before assignment [OK]
Hint: Always initialize map with make() before adding keys [OK]
Common Mistakes:
Forgetting to initialize map before use
Assuming declaration alone creates map
Confusing map initialization with slice
5. You want to implement a HashMap from scratch in Go without using built-in maps. Which of the following is the best approach to handle collisions?
hard
A. Ignore collisions and store only one key-value pair per bucket
B. Overwrite existing key-value pair without checking
C. Use a linked list at each bucket to store multiple key-value pairs
D. Use an array of fixed size without hashing keys
Solution
Step 1: Understand collision in HashMap
When two keys hash to the same bucket, collision occurs and must be handled to store both pairs.
Step 2: Evaluate collision handling methods
Using a linked list at each bucket allows storing multiple pairs safely. Overwriting loses data, ignoring collisions loses data, and fixed arrays without hashing lose efficiency.
Final Answer:
Use a linked list at each bucket to store multiple key-value pairs -> Option C
Quick Check:
Separate chaining with linked lists handles collisions [OK]
Hint: Use linked lists per bucket to handle collisions [OK]
Common Mistakes:
Overwriting values on collision
Ignoring collisions causing data loss
Not using hashing for key distribution
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.