15% off all plans & roadmaps Use code

See plans

Reverse String

Updated

TL;DR: Reverse the character array in place by swapping the two ends and moving inward. Two pointers finish in O(n) time with O(1) extra space, while a reversed copy would need O(n) space.

Problem

Write a function that reverses a string. The string arrives as an array of characters, s.

Change the array in place. You may use only O(1) extra memory.

Example 1

Input: s = ["h", "e", "l", "l", "o"]
Output: ["o", "l", "l", "e", "h"]

Example 2

Input: s = ["H", "a", "n", "n", "a", "h"]
Output: ["h", "a", "n", "n", "a", "H"]

Constraints

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

Constraints that matter

  • n up to 10^5 rules out any O(n^2) approach, which could take about 10^10 steps in the worst case.
  • The O(1) memory limit rules out building a reversed copy, so every change has to happen inside s.
  • Each slot holds one printable ASCII character, so you swap whole elements and never split characters.
  • An odd length leaves one middle element in place, so the loop must stop cleanly when the pointers meet on that element.

View on LeetCode

Hints

Hint 1

Reversing a string means mirroring it.

Hint 2

The beginner's version builds the answer somewhere else first.

Solution

Intuition

Reversing a string means mirroring it. The first character goes to the last slot, the second goes to the second-to-last slot, and so on. Each index i has one partner, index n - 1 - i, and the two values trade places.

Picture two people at opposite ends of a bench of name cards, swapping their cards and then stepping toward each other. The left person is the left pointer, the right person is the right pointer, and each swap is one mirrored pair.

That partner structure points to the two pointers pattern. Put one index at the left end and one at the right end. Swap the values they point at, then move both indices inward. The next pair to visit is always the next pair inward.

The pointers stop when they meet or cross. By then every mirrored pair has swapped exactly once. The swap needs only one temporary value, so no extra array is required.

Watch the pattern animation

Worked example

Input: s = ["H", "a", "n", "n", "a", "h"]
Output: ["h", "a", "n", "n", "a", "H"]
Explanation: The first and last characters swap, then the second and second-to-last, and so on. The inner pairs are equal, so those swaps change nothing visible. The result is the mirror image of the input.

Approach 1: Brute force with a reversed copy

The beginner's version builds the answer somewhere else first. Read the input from the last index to the first, and append each character to a new list. Then copy the new list back into s.

This version is correct and easy to reason about. It breaks the memory rule, because the new list holds n characters at the same time as the input.

Steps

  1. Create an empty list out.
  2. Loop i from n - 1 down to 0 and append s[i] to out.
  3. Loop i from 0 to n - 1 and set s[i] to out[i].
  4. Return nothing. The caller sees the change because s was modified.

Dry run

Start with s = ["H", "a", "n", "n", "a", "h"]. Reading from the end, out grows as follows.

is[i]out after append
5h[h]
4a[h, a]
3n[h, a, n]
2n[h, a, n, n]
1a[h, a, n, n, a]
0H[h, a, n, n, a, H]

The copy loop then writes out[0] through out[5] back into s. The array becomes ["h", "a", "n", "n", "a", "H"], which matches the expected output.

Complexity

TimeO(n)
SpaceO(n)

Let n be the array length. The first loop runs n times, and the second loop runs n times, so the total work is 2n, which is O(n). The list out holds n characters at its peak, so the extra space is O(n). That extra space is exactly what the problem forbids.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """Do not return anything; modify s in-place instead."""
        # Build the reversed characters in a new list
        out = []
        for i in range(len(s) - 1, -1, -1):
            out.append(s[i])
        # Copy them back so the caller sees the change
        for i in range(len(s)):
            s[i] = out[i]

The String Reversal infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

String Reversal

Part of Two Pointers

Approach 2: Two pointers, swap from both endsOptimalString Reversal

What's slow in the copy approach is the second array. Every character is written twice, once into out and once back into s. The insight that fixes it: each character only needs one swap with its mirror partner. Swapping inside s removes the copy entirely.

Place left at index 0 and right at index n - 1. Swap the two values, then move left right and right left. Stop when left is no longer less than right.

The pointers only meet in the middle, so each mirrored pair is swapped exactly once.

Why it is correct. After each step, the outer pairs already hold their final characters, and the unvisited middle keeps its original order. Each index has exactly one mirror partner, so no position is skipped or swapped twice.

Steps

  1. Set left to 0 and right to n - 1.
  2. While left < right, swap s[left] and s[right].
  3. Add 1 to left and subtract 1 from right.
  4. When the loop ends, s holds the reversed characters. Return nothing.

Dry run

Start with s = ["H", "a", "n", "n", "a", "h"], left = 0, and right = 5. The table shows the state at the check at the top of each pass.

Checkleftrightleft < right?Actions at this check
105yesswap H and h[H, a, n, n, a, h]
214yesswap a and a[h, a, n, n, a, H]
323yesswap n and n[h, a, n, n, a, H]
432nostop[h, a, n, n, a, H]

The last row shows the loop ends with s equal to the expected output.

Complexity

TimeO(n)
SpaceO(1)

Let n be the array length. The loop body runs once per mirrored pair, which is floor(n / 2) times. Each pass does two reads, two writes and two pointer updates, all constant time, so the total time is O(n). The method keeps two integer indices and a temporary value, and that count does not grow with n, so the space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """Do not return anything; modify s in-place instead."""
        left, right = 0, len(s) - 1
        # Swap mirrored pairs until the pointers meet or cross
        while left < right:
            s[left], s[right] = s[right], s[left]
            left += 1
            right -= 1

Common mistakes

  • Looping while left < n instead of while left < right. Past the middle, each pair swaps a second time and undoes the first half. Fix: stop when the pointers meet, so each pair swaps once.
  • Writing s[left] = s[right]; s[right] = s[left]; with no temporary. The second line reads the value the first line already overwrote, so both slots hold the same character. Fix: save one value first, or use a tuple swap in Python.
  • Writing s = s[::-1] inside the method in Python. The slice builds a new list, and the name s now points to it, so the caller's list does not change. Fix: swap elements through their indices. s[:] = s[::-1] also works, but it builds an O(n) copy.
  • Starting right at n instead of n - 1. The first swap reads one index past the end, which raises an IndexError in Python or an ArrayIndexOutOfBoundsException in Java. Fix: start at len(s) - 1 or s.length - 1.
  • Reassigning the parameter in Go or C#, for example s = out in Go. The parameter is a local copy of the slice or array reference, so the caller still sees the old elements. Fix: write into the existing elements with an index loop or copy.

Edge cases

  • Length 1, for example ["a"]. The loop never runs, and the output equals the input.
  • Length 2, for example ["a", "b"]. One swap gives ["b", "a"].
  • Odd length, for example ["a", "b", "c"]. The result is ["c", "b", "a"], and the middle b stays in place.
  • All characters equal, for example ["x", "x", "x", "x"]. Each swap changes nothing visible, and the output matches the input.
  • Palindrome, for example ["r", "a", "c", "e", "c", "a", "r"]. The reversed string equals the original, so the array stays the same.
  • Maximum length 100000 with space or quote characters. Each character follows the same rule, so the loop does about 50000 swaps with no special cases.

Follow-ups interviewers ask

What if you must reverse the string recursively?
Swap the outer pair, then recurse on the inner range. It is correct, but the call depth is n / 2. With n equal to 10^5, Python's default recursion limit of about 1000 fails, and the call stack adds O(n) space. Stay with the iterative loop.
What if the input is a singly linked list of characters?
You cannot walk two ends at once, and you cannot step backwards. Reverse the list by relinking pointers with three variables, prev, current and next. That keeps the extra space at O(1), and the time is O(n).
How would you reverse each word in place inside a sentence?
Reverse the whole character array first. Then reverse the range of each word again to restore its letters. Each character is touched a fixed number of times, so the total time is O(n) with O(1) extra space.

Reverse String FAQ

What is the time complexity of Reverse String?

The time is O(n), where n is the array length. The loop runs about n / 2 times with constant work each time. Any correct solution must touch every slot, so O(n) is the best possible.

Why use two pointers for Reverse String?

Reversal pairs index i with index n - 1 - i. Two pointers, one at each end, visit exactly those pairs in order. The pointers move inward together, so the work stays linear and the memory stays constant.

Can Reverse String be solved in O(1) extra space?

Yes. The two-pointer solution keeps two integer indices and one temporary value. The reversed-copy approach needs O(n) extra space, so it fails the memory constraint.

Why can't I use s[::-1] in Python for this problem?

The slice creates a new list and rebinds the local name s. The caller's list does not change, and the copy uses O(n) memory. Swap elements through their indices instead.

Can I reverse the characters inside each string in Java or C#?

Not in place. Java and C# strings are immutable, so you cannot change their characters. This problem passes an array of String values, so the solution swaps references between slots. A char array would let you swap the characters directly.

Asked at

See which companies ask this — Pro

Practise it