Reverse String
Reverse String
Given a slice of bytes representing a string, reverse it in-place.
Function signature
func ReverseString(s []byte)
Inputs / outputs
s: byte slice to reverse.- Return: nothing; modify
sin-place.
Example
s = ['h','e','l','l','o']
After reverse: ['o','l','l','e','h']
Constraints
0 <= len(s) <= 100_000
Core idea (near-solution)
Use two pointers from both ends and swap until they cross.
Invariant: elements outside [l, r] are already in their final positions.
Algorithm (step-by-step)
- Set
l = 0,r = len(s)-1. - While
l < r:- Swap
s[l]ands[r]. - Increment
l, decrementr.
- Swap
- Done.
Correctness sketch
- Invariant: elements outside
[l, r]are already in their final positions. - Each step moves at least one pointer, shrinking the remaining search space.
- The invariant ensures elements outside the active window are already handled correctly.
- When pointers meet or cross, all candidates have been considered.
Trace (hand walkthrough)
Trace Walkthrough
Example input:
s = ['h','e','l','l','o']
After reverse: ['o','l','l','e','h']
Walk:
- l=0,r=4: swap h and o -> [o,e,l,l,h]
- l=1,r=3: swap e and l -> [o,l,l,e,h], done
Pitfalls to avoid
- Forgetting to handle empty slices.
- Confusing byte reversal with Unicode rune reversal (this function operates on bytes).
Complexity
- Time:
O(n). - Extra space:
O(1).
Implementation notes (Go)
[]bytereversal is correct for ASCII and raw bytes; Unicode requires rune handling.
Run tests to see results
No issues detected