Map creation in Go - Time & Space Complexity
When we create a map in Go, we want to know how the time it takes changes as the map gets bigger.
We ask: How does adding items to a map affect the time needed?
Analyze the time complexity of the following code snippet.
package main
func createMap(n int) map[int]int {
m := make(map[int]int)
for i := 0; i < n; i++ {
m[i] = i * 2
}
return m
}
This code creates a map and adds n key-value pairs, where each key is an integer and the value is double the key.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Inserting a key-value pair into the map inside the loop.
- How many times: Exactly n times, once for each number from 0 to n-1.
As n grows, the number of insertions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 insertions |
| 100 | 100 insertions |
| 1000 | 1000 insertions |
Pattern observation: The work grows directly with the number of items added.
Time Complexity: O(n)
This means the time to create the map grows in a straight line with the number of items added.
[X] Wrong: "Adding items to a map takes the same time no matter how many items are already there."
[OK] Correct: Each insertion takes some time, so more items mean more total time, even if each insert is fast.
Understanding how map creation time grows helps you explain how data structures behave as they get bigger, a useful skill in many coding situations.
"What if we changed the map to store slices instead of integers? How would the time complexity change?"
Practice
Solution
Step 1: Understand map creation syntax
In Go, the built-in functionmakeis used to create maps with specified key and value types.Step 2: Identify the correct syntax for an empty map
make(map[string]int)creates an empty map with string keys and int values.Final Answer:
m := make(map[string]int) -> Option AQuick Check:
Use make(map[keyType]valueType) to create maps [OK]
- Using new() instead of make() for maps
- Trying to create map with slice syntax
- Confusing map literal with empty slice
Solution
Step 1: Check key type validity
Map keys must be comparable types. Slices ([]int) are not comparable in Go.Step 2: Identify invalid map key type
Using[]intas a key type causes a syntax error because slices cannot be map keys.Final Answer:
m := make(map[[]int]string) -> Option CQuick Check:
Map keys must be comparable types [OK]
- Using slices or maps as map keys
- Confusing map literal with slice literal
- Ignoring key type restrictions
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 key-value pairs: "apple"=5 and "banana"=3.Step 2: Calculate the sum of values
Addingm["apple"](5) andm["banana"](3) results in 8.Final Answer:
8 -> Option BQuick Check:
5 + 3 = 8 [OK]
- Concatenating values as strings instead of adding
- Expecting zero for existing keys
- Forgetting to initialize map before use
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, so it is nil.Step 2: Understand runtime behavior
Assigning to a nil map causes a runtime panic (error) because the map is not ready to store values.Final Answer:
Map declared but not initialized, causes runtime panic -> Option DQuick Check:
Declare + make before use to avoid panic [OK]
- Forgetting to initialize map before assignment
- Assuming declaration alone creates usable map
- Confusing map declaration with slice declaration
keys := []string{"a", "b", "c"} and a slice of ints values := []int{1, 2, 3}, which code snippet correctly creates a map from keys to values?Solution
Step 1: Match keys and values correctly
Keys are strings, values are ints. The map must have type map[string]int.Step 2: Verify loop and assignment
m := make(map[string]int) for i := range keys { m[keys[i]] = values[i] } loops over keys and assignsm[keys[i]] = values[i], correctly pairing keys to values.Final Answer:
m := make(map[string]int) for i := range keys { m[keys[i]] = values[i] } -> Option AQuick Check:
Loop keys, assign values to map[key] [OK]
- Swapping keys and values in map assignment
- Using wrong map key or value types
- Not initializing map before assignment
Ready to prove it?
Pass the test and this pattern moves unknown
