Bird
Raised Fist0
Goprogramming~20 mins

Iterating over maps in Go - Practice Problems & Coding Challenges

Choose your learning style10 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.

Practice

(1/5)
1.

What does the range keyword do when used with a map in Go?

easy
A. It creates a copy of the map.
B. It sorts the map by keys before looping.
C. It only loops over the keys, ignoring values.
D. It allows you to loop over all key-value pairs in the map.

Solution

  1. Step 1: Understand the purpose of range with maps

    The range keyword in Go is used to iterate over elements in data structures like arrays, slices, and maps.
  2. Step 2: Identify what happens with maps

    When used with a map, range returns both the key and the value for each item in the map.
  3. Final Answer:

    It allows you to loop over all key-value pairs in the map. -> Option D
  4. Quick Check:

    range with map = loop keys and values [OK]
Hint: Remember: range gives key and value for maps [OK]
Common Mistakes:
  • Thinking range sorts the map
  • Assuming range only returns keys
  • Believing range copies the map
2.

Which of the following is the correct syntax to iterate over a map m in Go?

?
easy
A. for key, value := range m { /* code */ }
B. for (key, value) in m { /* code */ }
C. foreach key, value in m { /* code */ }
D. for key, value from m { /* code */ }

Solution

  1. Step 1: Recall Go's for-range syntax

    In Go, the correct way to loop over a map is using for key, value := range mapName.
  2. Step 2: Compare options

    Only for key, value := range m { /* code */ } uses the correct Go syntax with := and range keyword.
  3. Final Answer:

    for key, value := range m { /* code */ } -> Option A
  4. Quick Check:

    Go map iteration syntax = for key, value := range map [OK]
Hint: Use := with range to get key and value [OK]
Common Mistakes:
  • Using Python or JavaScript style loops
  • Missing := in the loop
  • Using wrong keywords like foreach or from
3.

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)
    }
}
medium
A. Either 'a 1\nb 2' or 'b 2\na 1' (order not fixed)
B. b 2\na 1
C. a 1\nb 2
D. Compilation error

Solution

  1. Step 1: Understand map iteration order in Go

    Maps in Go do not guarantee order when iterating. The keys can appear in any order.
  2. 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'.
  3. Final Answer:

    Either 'a 1\nb 2' or 'b 2\na 1' (order not fixed) -> Option A
  4. Quick Check:

    Map iteration order = unpredictable [OK]
Hint: Map order is random; output order varies [OK]
Common Mistakes:
  • Assuming map iteration order is fixed
  • Expecting sorted output
  • Thinking code causes error
4.

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)
}
medium
A. Using 'range' incorrectly; should be 'for each'.
B. Using '=' instead of ':=' in the for loop.
C. Missing parentheses around key and value.
D. Map 'm' is not declared.

Solution

  1. Step 1: Check the for loop variable declaration

    In Go, variables declared in a for-range loop must use ':=' to declare new variables.
  2. Step 2: Identify the incorrect operator

    The code uses '=' which is assignment, not declaration, causing a syntax error.
  3. Final Answer:

    Using '=' instead of ':=' in the for loop. -> Option B
  4. Quick Check:

    Use ':=' to declare loop variables [OK]
Hint: Use ':=' not '=' in for-range loops [OK]
Common Mistakes:
  • Using '=' instead of ':='
  • Adding parentheses around variables
  • Confusing 'range' with other keywords
5.

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?

hard
A. Use range but skip keys with zero values by deleting them from original map.
B. Use for key := range m and copy all keys regardless of value.
C. Create a new map and add pairs where value != 0 inside a for-range loop.
D. Sort the map and then filter keys with zero values.

Solution

  1. Step 1: Understand the goal

    We want a new map with only keys whose values are not zero.
  2. Step 2: Use for-range to check each key-value pair

    Iterate over m with for k, v := range m, and add to new map only if v != 0.
  3. Step 3: Avoid modifying original map

    Do not delete keys from original map during iteration; create a new map instead.
  4. Final Answer:

    Create a new map and add pairs where value != 0 inside a for-range loop. -> Option C
  5. Quick Check:

    Filter map by value using new map and for-range [OK]
Hint: Build new map, add only non-zero values in loop [OK]
Common Mistakes:
  • Deleting keys from map while iterating
  • Copying all keys without filtering
  • Trying to sort a map (not supported)
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard