Iterating over maps in Go - Time & Space Complexity
When we loop over a map in Go, we want to know how the time it takes changes as the map gets bigger.
We ask: How does the number of steps grow when the map has more items?
Analyze the time complexity of the following code snippet.
func printMap(m map[string]int) {
for key, value := range m {
fmt.Println(key, value)
}
}
This code goes through each item in the map and prints its key and value.
- Primary operation: Looping over each key-value pair in the map.
- How many times: Once for every item in the map.
As the map gets bigger, the number of print steps grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print steps |
| 100 | 100 print steps |
| 1000 | 1000 print steps |
Pattern observation: The work grows directly with the number of items in the map.
Time Complexity: O(n)
This means if the map doubles in size, the time to loop through it roughly doubles too.
[X] Wrong: "Looping over a map is always constant time because maps are fast."
[OK] Correct: While accessing one item is fast, looping visits every item, so time grows with map size.
Understanding how looping over maps scales helps you explain your code's speed clearly and confidently.
"What if we nested a loop inside this loop to compare every map item with every other? How would the time complexity change?"
Practice
What does the range keyword do when used with a map in Go?
Solution
Step 1: Understand the purpose of
Therangewith mapsrangekeyword in Go is used to iterate over elements in data structures like arrays, slices, and maps.Step 2: Identify what happens with maps
When used with a map,rangereturns both the key and the value for each item in the map.Final Answer:
It allows you to loop over all key-value pairs in the map. -> Option DQuick Check:
rangewith map = loop keys and values [OK]
- Thinking range sorts the map
- Assuming range only returns keys
- Believing range copies the map
Which of the following is the correct syntax to iterate over a map m in Go?
?
Solution
Step 1: Recall Go's for-range syntax
In Go, the correct way to loop over a map is usingfor key, value := range mapName.Step 2: Compare options
Only for key, value := range m { /* code */ } uses the correct Go syntax with := and range keyword.Final Answer:
for key, value := range m { /* code */ } -> Option AQuick Check:
Go map iteration syntax = for key, value := range map [OK]
- Using Python or JavaScript style loops
- Missing := in the loop
- Using wrong keywords like foreach or from
What will be the output of the following Go code?
package main
import "fmt"
func main() {
m := map[string]int{"a": 1, "b": 2}
for k, v := range m {
fmt.Println(k, v)
}
}Solution
Step 1: Understand map iteration order in Go
Maps in Go do not guarantee order when iterating. The keys can appear in any order.Step 2: Analyze the output possibilities
The code prints each key and value pair. The output could be 'a 1' then 'b 2' or 'b 2' then 'a 1'.Final Answer:
Either 'a 1\nb 2' or 'b 2\na 1' (order not fixed) -> Option AQuick Check:
Map iteration order = unpredictable [OK]
- Assuming map iteration order is fixed
- Expecting sorted output
- Thinking code causes error
Identify the error in this Go code snippet that tries to iterate over a map m:
for key, value = range m {
fmt.Println(key, value)
}Solution
Step 1: Check the for loop variable declaration
In Go, variables declared in a for-range loop must use ':=' to declare new variables.Step 2: Identify the incorrect operator
The code uses '=' which is assignment, not declaration, causing a syntax error.Final Answer:
Using '=' instead of ':=' in the for loop. -> Option BQuick Check:
Use ':=' to declare loop variables [OK]
- Using '=' instead of ':='
- Adding parentheses around variables
- Confusing 'range' with other keywords
Given a map m := map[string]int{"x": 0, "y": 2, "z": 0}, how can you create a new map containing only keys with non-zero values by iterating over m?
Solution
Step 1: Understand the goal
We want a new map with only keys whose values are not zero.Step 2: Use for-range to check each key-value pair
Iterate overmwithfor k, v := range m, and add to new map only ifv != 0.Step 3: Avoid modifying original map
Do not delete keys from original map during iteration; create a new map instead.Final Answer:
Create a new map and add pairs where value != 0 inside a for-range loop. -> Option CQuick Check:
Filter map by value using new map and for-range [OK]
- Deleting keys from map while iterating
- Copying all keys without filtering
- Trying to sort a map (not supported)
Ready to prove it?
Pass the test and this pattern moves unknown
