Challenge - 5 Problems
String Traversal Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediateOutput of rune traversal in Go string
What is the output of the following Go code that traverses a string using range and prints each rune's integer value?
DSA Go
package main import "fmt" func main() { s := "Goπ" for _, r := range s { fmt.Print(int(r), " ") } }
Attempts:
2 left
π‘ Hint
Remember that range over a string in Go iterates over runes, not bytes.
β Incorrect
The range loop over string s iterates over runes (Unicode code points). 'G' is 71, 'o' is 111, and the emoji π is a single rune with code point 128522.
β Predict Output
intermediateIndexing bytes vs runes in Go strings
What is the output of this Go code that prints bytes and runes of a string containing multibyte characters?
DSA Go
package main import "fmt" func main() { s := "Hiπ" fmt.Print("Bytes: ") for i := 0; i < len(s); i++ { fmt.Print(s[i], " ") } fmt.Print("\nRunes: ") for _, r := range s { fmt.Print(r, " ") } }
Attempts:
2 left
π‘ Hint
Bytes represent raw UTF-8 encoding, runes represent Unicode code points.
β Incorrect
The emoji π is encoded in UTF-8 as 4 bytes: 240, 159, 152, 138. The range loop reads it as one rune 128522.
π§ Conceptual
advancedWhy direct indexing on Go strings can be misleading
Why can using direct indexing (s[i]) on a Go string with multibyte characters lead to incorrect character access?
Attempts:
2 left
π‘ Hint
Think about UTF-8 encoding and how Go stores strings.
β Incorrect
Go strings are byte slices. Indexing returns a byte, not a full Unicode character (rune). Multibyte characters are multiple bytes, so indexing can split them.
β Predict Output
advancedOutput of string slicing with multibyte characters in Go
What is the output of this Go code that slices a string containing an emoji?
DSA Go
package main import "fmt" func main() { s := "Hiπ" fmt.Println(s[0:2]) fmt.Println(s[2:]) }
Attempts:
2 left
π‘ Hint
Remember slicing works on bytes, not runes, so slicing inside a multibyte character can cause invalid UTF-8.
β Incorrect
The first slice s[0:2] is bytes for 'H' and 'i'. The second slice s[2:] starts inside the emoji's 4-byte UTF-8 sequence, causing invalid UTF-8 and printing replacement character οΏ½.
π§ Debug
expertIdentify the error in rune counting code
What error will this Go code produce when counting runes in a string, and why?
DSA Go
package main import "fmt" func main() { s := "Helloπ" count := 0 for i := 0; i < len(s); i++ { if s[i] >= 128 { count++ } } fmt.Println(count) }
Attempts:
2 left
π‘ Hint
Consider what s[i] returns and how multibyte characters are encoded.
β Incorrect
s[i] accesses bytes, so the emoji's 4 bytes with values >= 128 are counted individually, resulting in 4 instead of 1 rune.
