Reverse a string so multi-byte UTF-8 characters stay intact
Implement reverse(s) returning s with its characters in reverse order. Requirement: multi-byte UTF-8 characters must stay intact — reversing the raw bytes would split a rune like é and produce invalid UTF-8. O(n) time. Example: reverse("héllo") → "olléh".
func reverse(s string) string {
// your code here
return ""
}
Write the implementation.
Convert the string to []rune first, then two-pointer swap from both ends and return string(r). Operating on runes keeps multi-byte characters whole — reversing the raw bytes would split a rune like é and corrupt it. The algorithm is O(n) time and O(n) space.
- ✗Reversing
[]byteinstead of[]rune, splitting multi-byte characters - ✗Assuming
rangeiterates a string in reverse - ✗Indexing
s[i]and treating each byte as a character
- →Why does reversing the byte slice of
hélloproduce invalid UTF-8? - →How would you reverse by grapheme cluster (e.g. an emoji with combining marks)?
Task
Reverse a string while handling Unicode correctly: multi-byte characters must stay intact.
func reverse(s string) string {
r := []rune(s) // operate on runes, not bytes
for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
// reverse("héllo") -> "olléh" (reversing bytes would corrupt "é")
Why operate on runes
A Go string is UTF-8 bytes. The character é is two bytes. If you reverse []byte, the two bytes of é swap independently and yield an invalid UTF-8 sequence — the character is destroyed.
Converting []rune(s) decodes the string into code points, so each character is one element. Two pointers swap elements from the ends toward the centre in O(n); string(r) re-encodes the runes back to UTF-8.
⚠️ This tests whether you know strings are byte sequences and that multi-byte characters must be reversed as runes.