Reverse String Go
Fast recall
Quick revision
Core answer
Whether you understand Reverse String Go beyond memorized syntax.
Giving a definition without explaining a practical trade-off.
Connect the concept to a small production example and state its complexity or failure mode.
Interview-ready guide
Interview answer
The correct form, executed:
func reverse(s string) string {
r := []rune(s)
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("hello") → "olleh" — verifiedThe trap: byte-reversal corrupts non-ASCII:
b := []byte("héllo")
// swap bytes → é's two bytes (195, 169) become (169, 195) — invalid UTF-8The mechanics: "héllo" is 6 bytes (é is 2). []rune decodes it into 5 code points. Reversing RUNES moves each CHARACTER as a unit. Byte reversal splits the rune — the output is garbage. The strings topic covers the full UTF-8 story.
The costs: []rune(s) allocates and decodes (O(n)); the swap is O(n/2); string(r) re-encodes (O(n)). Three passes — the honest cost of Unicode correctness.
Reverse String Go
Direct Answer
[]rune(s) + swap ends inward — rune-safe. Byte reversal corrupts multibyte UTF-8 (é's two bytes reversed = garbage). Verified: "hello" → "olleh".
Deep Dive & Architecture
The grapheme caveat for the perfect answer: rune reversal reverses code points, not graphemes — "é" as e + combining-accent (two runes) stays reversed as accent + e (the accent attaches to the wrong character). True grapheme-safe reversal needs a segmenter (x/text or uniseg). For interviews, rune-reversal with the grapheme caveat is the complete answer.
The allocation-free alternative for hot paths: walk both ends simultaneously with utf8.DecodeRuneInString (forward) and utf8.DecodeLastRuneInString (backward) — swapping into a pre-allocated []byte. Zero rune-slice allocation. The readable []rune version is the default; the optimized version only when profiling demands.
The interview short-circuit: this question is really 'do you know strings are bytes + runes exist?' — the candidate who reaches for []byte(s) without mentioning the trap, or reverses bytes without knowing the corruption, reveals the gap.
Common Mistakes & Pitfalls
Giving a definition without explaining a practical trade-off.
Check your understanding
Answer these without looking back at the article.
- When would you use Reverse String Go in a real project?
- How would you compare Reverse String Go with an alternative?
- What is a common mistake when using Reverse String Go?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.