Community Problem

Reverse String

Difficulty: Easy

Reverse a character array in place using two pointers, no extra buffer allowed.

Reverse String

Reverse a character array in place using two pointers, no extra buffer allowed.

EASY
Free
strings
two-pointers
fundamentals

By CodeSnatch

January 17, 2026

·

Updated May 18, 2026

354 views

1

4.4 (9)

First two-pointer problem I hand a junior who claims they "already know strings". It looks trivial in Python (s[::-1]) but the in-place constraint forces the swap-with-two-pointers muscle that every later sliding-window problem leans on. It also shows up in real work more often than people credit: reversing a ring-buffer dump for tail-style log inspection, flipping a byte array before a checksum, or undoing a stack push order without allocating a second buffer. The official practice catalog jumps straight to Valid Palindrome and Is Subsequence; this is the missing 5-minute warm-up.

Reverse String

Given an input array of characters s, reverse it in place. You must do this with O(1) extra memory (the swap variable does not count).

Examples

Example 1:

  • Input: s = ["h", "e", "l", "l", "o"]
  • Output: ["o", "l", "l", "e", "h"]
  • Explanation: Five swaps if you walk every index, two swaps if you stop the pointers at the middle.

Example 2:

  • Input: s = ["H", "a", "n", "n", "a", "h"]
  • Output: ["h", "a", "n", "n", "a", "H"]
  • Explanation: Even-length array, the two pointers cross between indices 2 and 3.

Example 3:

  • Input: s = ["A"]
  • Output: ["A"]
  • Explanation: Single element, the loop body never executes.

Example 4:

  • Input: s = ["a", "b"]
  • Output: ["b", "a"]
  • Explanation: Smallest non-trivial case, exactly one swap.

Constraints

  • 1 <= s.length <= 10^5
  • s[i] is a printable ASCII character.

Follow-up

Can you do it without using a temporary swap variable? (XOR swap on character codes is the usual answer, though it is rarely worth the readability cost in production code.)

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems