Reverse String

easy · strings, two-pointers

Reverse String

Given a slice of bytes representing a string, reverse it in-place.

Why this is worth learning

Reversal pairs each original position i with n-1-i. This direct position mapping supplies both an implementation and a simple involution property for testing.

Before coding: one-minute experiment

What happens to the two bytes 0xC3 and 0xA9, and why is that not a Unicode-character reversal?

Function signature

func ReverseString(s []byte)

Inputs / outputs

  • s: byte slice to reverse.
  • Return: nothing; modify s in-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)

  1. Set l = 0, r = len(s)-1.
  2. While l < r:
    • Swap s[l] and s[r].
    • Increment l, decrement r.
  3. Done.

Correctness sketch

Before swapping l and r=n-1-l, all positions outside [l,r] already contain their required original symmetric values. The two endpoint values have not yet been moved, so swapping them installs both correct values and preserves the interior. Advancing l and reducing r extends the finalized region by two. An odd-length center maps to itself and needs no swap. After floor(n/2) swaps, every position is final. The procedure changes only the caller's bytes and uses a constant number of indices.

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).

Debugging lens

Test empty, odd, even, repeated, and non-ASCII raw byte slices. Reverse twice to recover the original, but also compare one reversal with the expected mapping: doing nothing also passes a double-reversal test.

Complexity

  • Time: O(n).
  • Extra space: O(1).

Implementation notes (Go)

  • []byte reversal is correct for ASCII and raw bytes; Unicode requires rune handling.

Reconstruction checkpoint

What happens to the two bytes 0xC3 and 0xA9, and why is that not a Unicode-character reversal?

Model answer

They become 0xA9,0xC3. The function reverses raw bytes, even when those bytes originally encoded a single UTF-8 character.

Return to Two Pointers · Module quiz

Run tests to see results
No issues detected
    Join Discord