0
0
Goprogramming~20 mins

Iterating over maps in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Map Iteration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of iterating over a map with range
What is the output of this Go program?
Go
package main
import "fmt"
func main() {
    m := map[string]int{"a": 1, "b": 2, "c": 3}
    for k, v := range m {
        fmt.Printf("%s:%d ", k, v)
    }
}
AThe output order is random but all key:value pairs are printed separated by spaces
Bc:3 b:2 a:1
Ca:1 b:2 c:3
DCompilation error due to map iteration
Attempts:
2 left
💡 Hint
Maps in Go do not guarantee order when iterating.
Predict Output
intermediate
2:00remaining
Counting items in a map during iteration
What is the value of count after running this Go code?
Go
package main
import "fmt"
func main() {
    m := map[int]string{1: "one", 2: "two", 3: "three"}
    count := 0
    for range m {
        count++
    }
    fmt.Println(count)
}
ARuntime panic
B0
C3
DCompilation error due to missing variables in range
Attempts:
2 left
💡 Hint
Range over a map iterates over all keys.
Predict Output
advanced
2:00remaining
Modifying map values during iteration
What is the output of this Go program?
Go
package main
import "fmt"
func main() {
    m := map[string]int{"x": 1, "y": 2}
    for k := range m {
        m[k] = m[k] * 10
    }
    fmt.Println(m)
}
Amap[x:1 y:2]
Bmap[x:10 y:20]
CCompilation error: cannot assign to map element during iteration
DRuntime panic: concurrent map iteration and map write
Attempts:
2 left
💡 Hint
You can modify map values during iteration safely in Go.
Predict Output
advanced
2:00remaining
Iterating over a nil map
What happens when this Go code runs?
Go
package main
import "fmt"
func main() {
    var m map[string]int
    for k, v := range m {
        fmt.Println(k, v)
    }
    fmt.Println("Done")
}
APrints nothing then prints "Done"
BRuntime panic: nil map iteration
CCompilation error: map not initialized
DInfinite loop
Attempts:
2 left
💡 Hint
Iterating over a nil map is safe and acts like empty map.
🧠 Conceptual
expert
2:00remaining
Why is map iteration order random in Go?
Which reason best explains why Go's map iteration order is randomized?
ATo guarantee keys are sorted alphabetically during iteration
BBecause Go does not allow iteration over maps
CBecause Go maps are implemented as linked lists which have no order
DTo prevent programs from relying on order and to improve security by avoiding predictable iteration
Attempts:
2 left
💡 Hint
Think about why predictable order might be a problem.