Map use cases in Go - Time & Space Complexity
Maps in Go help us store and find data quickly using keys. Understanding how fast these operations run is important when working with many items.
We want to know how the time to find or add items changes as the map grows.
Analyze the time complexity of the following code snippet.
package main
func countWords(words []string) map[string]int {
counts := make(map[string]int)
for _, word := range words {
counts[word]++
}
return counts
}
This code counts how many times each word appears in a list using a map.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each word in the list and updating the map.
- How many times: Once for each word in the input list.
Each word is processed once, and the map updates happen quickly on average regardless of size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 map updates |
| 100 | About 100 map updates |
| 1000 | About 1000 map updates |
Pattern observation: The work grows directly with the number of words, not more or less.
Time Complexity: O(n)
This means the time to count words grows in a straight line with the number of words.
[X] Wrong: "Using a map makes the code run in constant time no matter how many words there are."
[OK] Correct: Each word still needs to be processed once, so time grows with the list size, not fixed.
Knowing how maps work helps you explain efficient data lookups clearly, a useful skill in many coding tasks.
"What if we used a slice instead of a map to count words? How would the time complexity change?"
Practice
map in Go?Solution
Step 1: Understand the purpose of a map
A map in Go is a collection of key-value pairs, designed for fast data retrieval using keys.Step 2: Compare with other options
Options B, C, and D describe unrelated tasks like calculations, UI, or file handling, which are not the main use of maps.Final Answer:
To store data with keys for fast lookup -> Option AQuick Check:
Maps = key-value storage [OK]
- Confusing maps with slices or arrays
- Thinking maps are for calculations
- Assuming maps handle UI or files
Solution
Step 1: Identify map creation syntax
In Go, maps are created usingmake(map[keyType]valueType). var m map[string]int = make(map[string]int) uses this correctly.Step 2: Check other options
m := []int{} creates a slice, not a map. m := map[string]int is invalid syntax for map creation. m := make([]string, 0) creates a slice, not a map.Final Answer:
var m map[string]int = make(map[string]int) -> Option BQuick Check:
Use make() to create maps [OK]
- Using slice syntax instead of map syntax
- Not using make() to initialize maps
- Confusing map and slice creation
m := make(map[string]int) m["apple"] = 5 m["banana"] = 3 fmt.Println(m["apple"] + m["banana"])
Solution
Step 1: Understand map assignments
The mapmstores integers with string keys. "apple" maps to 5, "banana" maps to 3.Step 2: Calculate the sum
Adding m["apple"] + m["banana"] equals 5 + 3 = 8.Final Answer:
8 -> Option AQuick Check:
5 + 3 = 8 [OK]
- Concatenating values as strings
- Expecting zero for existing keys
- Thinking code causes error
var m map[string]int m["key"] = 10 fmt.Println(m["key"])
Solution
Step 1: Check map initialization
The mapmis declared but not initialized withmake(). This causes a runtime panic on assignment.Step 2: Understand consequences
Without initialization,m["key"] = 10causes a panic: assignment to nil map.Final Answer:
Map is not initialized with make() before use -> Option CQuick Check:
Initialize maps with make() [OK]
- Forgetting to initialize map before use
- Assuming declaration is enough
- Misunderstanding map assignment rules
m := map[string]int{"a": 1, "b": 0, "c": 3}, which code snippet correctly checks if key "b" exists and its value is non-zero?Solution
Step 1: Understand map key existence check
Usingval, ok := m["b"]lets us check if key "b" exists (ok) and get its value (val).Step 2: Check value is non-zero
The conditionok && val != 0ensures key exists and value is not zero.Final Answer:
if val, ok := m["b"]; ok && val != 0 { fmt.Println("Exists and non-zero") } -> Option DQuick Check:
Check key existence and value together [OK]
- Checking value without verifying key existence
- Assuming zero means key missing
- Using only ok without value check
Ready to prove it?
Pass the test and this pattern moves unknown
