Go Program to Reverse a String with Example and Explanation
rune slice, swap characters from both ends using a loop, and then convert it back to a string, like this: runes := []rune(s); for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] }; reversed := string(runes).Examples
How to Think About It
Algorithm
Code
package main import "fmt" func reverseString(s string) string { runes := []rune(s) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return string(runes) } func main() { input := "hello" fmt.Println(reverseString(input)) }
Dry Run
Let's trace reversing the string "hello" through the code
Convert string to runes
Input string: "hello" -> runes: ['h', 'e', 'l', 'l', 'o']
Initialize pointers
i = 0 (points to 'h'), j = 4 (points to 'o')
Swap runes at i and j
Swap 'h' and 'o' -> runes: ['o', 'e', 'l', 'l', 'h']
Move pointers
i = 1 (points to 'e'), j = 3 (points to 'l')
Swap runes at i and j
Swap 'e' and 'l' -> runes: ['o', 'l', 'l', 'e', 'h']
Move pointers
i = 2, j = 2 (both point to 'l'), stop swapping
Convert runes back to string
Result string: "olleh"
| i | j | runes |
|---|---|---|
| 0 | 4 | ['o', 'e', 'l', 'l', 'h'] |
| 1 | 3 | ['o', 'l', 'l', 'e', 'h'] |
| 2 | 2 | ['o', 'l', 'l', 'e', 'h'] |
Why This Works
Step 1: Convert to rune slice
Using []rune converts the string to runes so that multi-byte characters are handled correctly.
Step 2: Swap characters
Swapping runes from the start and end moves characters to their reversed positions.
Step 3: Convert back to string
After swapping, converting the rune slice back to a string gives the reversed string output.
Alternative Approaches
package main import "fmt" func reverseASCII(s string) string { b := []byte(s) for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { b[i], b[j] = b[j], b[i] } return string(b) } func main() { fmt.Println(reverseASCII("hello")) }
package main import "fmt" func reverseRec(s string) string { runes := []rune(s) if len(runes) <= 1 { return s } return string(runes[len(runes)-1]) + reverseRec(string(runes[:len(runes)-1])) } func main() { fmt.Println(reverseRec("hello")) }
Complexity: O(n) time, O(n) space
Time Complexity
The algorithm loops through half of the string length swapping characters, so it runs in linear time O(n).
Space Complexity
Converting the string to a rune slice requires O(n) extra space to hold the characters.
Which Approach is Fastest?
The rune slice swap method is efficient and safe for all characters. The byte slice method is faster but only works for ASCII. Recursive methods are slower due to overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Rune slice swap | O(n) | O(n) | All Unicode strings, safe and efficient |
| Byte slice swap | O(n) | O(n) | ASCII strings only, faster but limited |
| Recursive reversal | O(n^2) | O(n^2) | Small strings, simple code but inefficient |