EasyTwo Pointers

Reverse String โ€” Solution

Problem

Given an array of characters, reverse it in-place using O(1) extra memory โ€” you cannot allocate a new array to hold the result. The modification must happen directly on the input array.

  • Input: s = ["h","e","l","l","o"]
  • Output: ["o","l","l","e","h"]
  • Explanation: Characters are swapped from both ends toward the center until the whole array is reversed.

Intuition

The key constraint is that no extra array is allowed, so we need to rearrange characters in the original array. Placing a pointer at each end and swapping inward achieves this in one pass โ€” by the time the two pointers meet in the middle, every character has been moved to its correct reversed position.

Solution โ€” Two Pointers

Place one pointer at the start and one at the end. Swap the characters they point to, then advance both pointers toward the center. Stop when they meet or cross.

  1. Initialize left = 0 and right = len(s) - 1.
  2. While left < right:
    • Swap s[left] and s[right].
    • Increment left; decrement right.
  3. The array is now reversed in-place.
1def reverseString(s: list[str]) -> None:
2    left, right = 0, len(s) - 1
3    while left < right:
4        s[left], s[right] = s[right], s[left]  # swap without a temp variable
5        left += 1
6        right -= 1

Time: O(n) โ€” each character is visited exactly once.

Space: O(1) โ€” only two index variables; no auxiliary storage.

Complexity Summary

ApproachTimeSpaceWhen to use
Two Pointers (in-place)O(n)O(1)Any time in-place reversal is required

Common Mistakes

  • Using s[::-1] in Python โ€” this creates a brand-new list rather than modifying the existing array, which violates the O(1) space constraint and won't update the caller's array.
  • Returning a value instead of modifying in-place โ€” the function signature is void; returning a reversed copy gets the right output but misses the point of the problem.
  • Using left <= right as the loop condition โ€” when the array has an odd length, the middle element gets swapped with itself (harmless, but unnecessary); left < right is the correct and cleaner termination.
  • Allocating a temporary char[] or list for the swap โ€” a simple three-variable swap or Python's simultaneous assignment is all that's needed.

Related Problems

Ready to practice? Try it on SkillFlow

Adaptive problems, AI follow-up interviews, and a skill score that shows exactly where you need to improve.

Practice This Problem โ†’