Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to reverse a string using a for loop.
DSA Go
func reverseString(s string) string {
result := ""
for i := len(s) - 1; i >= [1]; i-- {
result += string(s[i])
}
return result
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 instead of 0 as the loop boundary causes the first character to be skipped.
Using len(s) causes index out of range error.
✗ Incorrect
The loop should start from the last index (len(s)-1) and go down to 0 to include the first character.
2fill in blank
mediumComplete the code to reverse a string by converting it to a rune slice.
DSA Go
func reverseString(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, [1] {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}Attempts:
3 left
💡 Hint
Common Mistakes
Incrementing j causes the loop to never end or swap incorrectly.
Using j without change causes an infinite loop.
✗ Incorrect
To swap characters from both ends, j should decrease by 1 each iteration.
3fill in blank
hardFix the error in the code that attempts to reverse a string using a byte slice.
DSA Go
func reverseString(s string) string {
bytes := []byte(s)
for i := 0; i < len(bytes)/2; i++ {
j := len(bytes) - i - [1]
bytes[i], bytes[j] = bytes[j], bytes[i]
}
return string(bytes)
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 causes swapping with an invalid index.
Using i or 2 causes wrong indices and runtime errors.
✗ Incorrect
To get the correct index from the end, subtract i and 1 from length.
4fill in blank
hardFill both blanks to create a map of characters to their reversed positions.
DSA Go
func charPositions(s string) map[rune]int {
positions := make(map[rune]int)
for i, r := range s {
positions[r] = [1] - i - [2]
}
return positions
}Attempts:
3 left
💡 Hint
Common Mistakes
Using len(s) instead of len(s)-1 causes off-by-one errors.
Subtracting i incorrectly shifts positions.
✗ Incorrect
The reversed position is length minus 1 minus current index i, so subtract 0 after.
5fill in blank
hardFill both blanks to create a reversed string using a builder and rune slice.
DSA Go
import "strings" func reverseString(s string) string { runes := []rune(s) var builder strings.Builder for i := len(runes) - 1; i >= [1]; i-- { builder.WriteRune(runes[[2]]) } return builder.String() }
Attempts:
3 left
💡 Hint
Common Mistakes
Looping down to 1 skips the first character.
Writing runes at wrong index causes incorrect output.
✗ Incorrect
Loop down to 0, write runes at index i, and return the built string.
