In-Place Character List Reversal

Medium · Coding & Algorithms · Data Scientist · Technical Screen

Problem Statement

Given s, a mutable Python list of single-character strings, reverse the order of its elements directly inside s and return None.

from typing import List


def reverse_string(s: List[str]) -> None:
    ...

Your implementation must rearrange elements in place using O(1) auxiliary memory. Do not invoke built-in reversal utilities (list.reverse(), reversed()), copy or replace slices (s[::-1], s[:] = ...), call s.copy(), or allocate another list proportional to the length of s.

Examples

Example 1

  • Input: s = ["p", "l", "a", "n", "t"]
  • Output: s is mutated to ["t", "n", "a", "l", "p"] (returns None)
  • Explanation: Outer indices 0 ("p") and 4 ("t") trade places first, then indices 1 ("l") and 3 ("n") trade places. Index 2 ("a") sits at the middle and stays put.

Example 2

  • Input: s = ["G", "r", "a", "p", "h", "7"]
  • Output: s is mutated to ["7", "h", "p", "a", "r", "G"] (returns None)
  • Explanation: Three mirrored swaps — (0, 5), (1, 4), and (2, 3) — reverse every pair until the front and back indices cross at the center.

Constraints

  • 1 <= len(s) <= 10^5 (your code should also avoid crashing on an empty list []).
  • Each element s[i] is a single printable ASCII character (code points 32 through 126).
  • Auxiliary space must be O(1) beyond the input list itself.

Step-by-step walkthrough

  1. Understand the in-place contract

    We are given s, a Python list of single-character strings (1 <= len(s) <= 10^5), and asked to reverse the order of its elements in place and return None.

    Two rules shape everything we write:

    • In-place mutation: An in-place algorithm modifies the caller's existing list object directly instead of returning a brand-new list. Note a classic Python trap: writing s = s[::-1] inside reverse_string(s) only points the local variable name s at a new list, leaving the caller's original list completely unchanged!
    • O(1) extra memory (constant auxiliary space): Our extra working memory must stay a small, fixed number of variables whether len(s) is 5 or 100,000. Built-in shortcuts like s.reverse(), reversed(s), slicing (s[::-1]), or copying s into a helper list are all off-limits.
  2. Why the naive copy-and-overwrite approach breaks the space rule

    If extra memory were free, the most direct idea would read s backward into a second list and copy the characters back into s:

    def reverse_with_copy(s):
        # Builds a second list of length n -> O(n) extra memory (not allowed!)
        reversed_copy = []
        for i in range(len(s) - 1, -1, -1):
            reversed_copy.append(s[i])
        for i in range(len(s)):
            s[i] = reversed_copy[i]
    

    This runs in O(n) time — which we cannot beat, because every character has to move — but reversed_copy stores n elements at once (O(n) extra space). To drop extra space down to O(1), we need to rearrange characters directly inside s.

  3. Key idea: two pointers swapping mirrored ends

    Look at where each character needs to end up: the first character (index 0) trades places with the last character (index n - 1), the second character (index 1) trades places with the second-to-last (index n - 2), and in general index i trades places with index n - 1 - i.

    Index:     0     1     2     3     4
             +-----+-----+-----+-----+-----+
    s:       | "p" | "l" | "a" | "n" | "t" |
             +-----+-----+-----+-----+-----+
                ^                       ^
                |                       |
              left = 0               right = 4     (outer pair swaps first)
    

    Using the two-pointer technique — maintaining two integer indices left and right that move coordinately across an array — we only ever need three tiny variables (left, right, and a 1-character temp slot for the swap):

    1. Start left = 0 and right = len(s) - 1.
    2. Swap s[left] and s[right] using temp.
    3. Advance left += 1 and right -= 1 one step toward the center.

    At the start of every loop iteration, our loop invariant (a property guaranteed to hold before and after every step) is simple: everything strictly left of left (s[:left]) and strictly right of right (s[right + 1:]) is already in its final reversed position, while s[left : right + 1] still needs to be reversed.

  4. Why while left < right handles both odd and even lengths

    When should the loop stop? Check what happens at the center for both odd and even array lengths:

    Odd length (n = 5):                   Even length (n = 4):
      iter 1: left=0, right=4 (swap)        iter 1: left=0, right=3 (swap)
      iter 2: left=1, right=3 (swap)        iter 2: left=1, right=2 (swap)
      next  : left=2, right=2 -> STOP!      next  : left=2, right=1 -> STOP!
              (pointers meet on middle)             (pointers cross each other)
    
    • Odd length (n = 5): After swapping (0, 4) and (1, 3), both pointers land on index 2 (left == right). A single middle character is its own mirror image, so no swap is needed and we stop.
    • Even length (n = 4): After swapping (0, 3) and (1, 2), left becomes 2 and right becomes 1 (left > right). The pointers have crossed, meaning every pair has been swapped once, so we stop.
    • Length 1 (or empty list): For n = 1, left = 0 and right = 0; for n = 0, left = 0 and right = -1. In both cases left < right is immediately False, so the loop safely does zero swaps!

    Keep while left < right: as the condition. If you kept looping past the midpoint (for example for left in range(len(s)):), you would swap every pair a second time and undo the reversal!

  5. Trace Example 1 and Example 2 step by step

    Tracing s = ["p", "l", "a", "n", "t"] (n = 5, odd length):

    Step   left   right   left < right?   Action                  Array state after step
    init     0      4         True        ready to start          ["p", "l", "a", "n", "t"]
      1      0      4         True        swap s[0] <-> s[4]      ["t", "l", "a", "n", "p"]
      2      1      3         True        swap s[1] <-> s[3]      ["t", "n", "a", "l", "p"]
      3      2      2         False       stop (met at middle)    ["t", "n", "a", "l", "p"]
    

    Tracing s = ["G", "r", "a", "p", "h", "7"] (n = 6, even length):

    Step   left   right   left < right?   Swapped pair   Array state after step
      1      0      5         True        "G" <-> "7"    ["7", "r", "a", "p", "h", "G"]
      2      1      4         True        "r" <-> "h"    ["7", "h", "a", "p", "r", "G"]
      3      2      3         True        "a" <-> "p"    ["7", "h", "p", "a", "r", "G"]
      4      3      2         False       stop (crossed) ["7", "h", "p", "a", "r", "G"]
    

    Notice that a list of length n always performs exactly n // 2 swaps (2 swaps for n = 5, 3 swaps for n = 6).

  6. Complete solution

    Putting the initialization, loop condition, three-line in-place swap (you could also write Python's tuple swap s[left], s[right] = s[right], s[left], which does the same constant-space swap), and pointer updates together gives the complete implementation:

    from typing import List
    
    
    def reverse_string(s: List[str]) -> None:
        """Reverse the list of characters s in place and return None.
    
        Two pointers start at both ends and swap their characters while moving
        toward the middle: O(n) time, O(1) extra memory.
        """
        # left, right: integer index pointers starting at the front (0) and back (len(s) - 1)
        left = 0
        right = len(s) - 1
    
        # Loop invariant: s[:left] and s[right + 1:] already hold their final reversed characters.
        # Stop when left >= right so odd-length middles stay put and even-length pairs swap only once.
        while left < right:
            # Swap the mirrored pair s[left] and s[right] using a single O(1) temporary slot
            temp = s[left]
            s[left] = s[right]
            s[right] = temp
    
            # Move both pointers one position inward toward the center
            left += 1
            right -= 1
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a row of letter tiles ("p", "l", "a", "n", "t") lined up on a narrow shelf with no spare table space. Put your left hand on the first tile and your right hand on the last tile, swap the two tiles, and slide each hand one tile closer to the middle. Repeat until your hands touch on the center tile (or pass each other): the entire row is now reversed without ever needing a second shelf.

Beginners often write s = s[::-1] or build a reversed list result = [] and copy it back. Writing s = s[::-1] inside the function only rebinds the local variable name s to a new list while leaving the caller's original list untouched, and building any helper list of length n violates the O(1) extra space rule — the requirement that auxiliary memory stays constant regardless of input size. Using the two-pointer technique (two integer indices walking inward from opposite ends) performs an in-place reversal — mutating the caller's list directly — with just three scalar variables (left, right, and temp).

Here is how the pointers walk across s = ["p", "l", "a", "n", "t"] (n = 5):

  1. Start left = 0 ("p") and right = 4 ("t"). Since 0 < 4, swap them -> ["t", "l", "a", "n", "p"], then move to left = 1, right = 3.
  2. At left = 1 ("l") and right = 3 ("n"), 1 < 3, so swap them -> ["t", "n", "a", "l", "p"], then move to left = 2, right = 2.
  3. Now left == right == 2: 2 < 2 is False, so the loop stops, leaving the middle "a" untouched in its exact final spot and returning None.

Complexity

  • Time: O(n), where n = len(s). Each iteration moves left up by 1 and right down by 1, so the loop runs exactly n // 2 times and performs a constant-time (O(1)) swap and two integer updates per step.
  • Space: O(1) extra memory. Regardless of whether s has 1 character or 100,000 characters, we allocate only two integer indices (left, right) and one temporary reference (temp).

Edge cases

  • Single character (["x"]): left = 0 and right = 0, so left < right is immediately False; zero swaps run and ["x"] stays unchanged.
  • Two characters (["a", "b"]): Smallest even length — swaps (0, 1) once, then left = 1, right = 0 crosses and stops cleanly.
  • Odd vs. even lengths: Odd lengths stop when left == right at the center element; even lengths stop when left == right + 1 right after swapping the innermost pair.
  • Empty list ([], outside the 1 <= n constraint): left = 0 and right = -1, so 0 < -1 is False and the function safely returns None without raising IndexError.
  • Palindromes, duplicate characters, and punctuation (["r", "a", "c", "e", "c", "a", "r"], ["!", " "]): Swapping identical characters or symbols works identically without needing any special-case if s[left] != s[right] check.

Common mistakes

  • Rebinding the parameter (s = s[::-1]): Creates a new list and points only the local variable s to it; the caller's list is never modified. (Even slice assignment s[:] = s[::-1] mutates the caller's list, but still allocates an O(n) temporary slice copy.)
  • Looping all the way to n - 1: Iterating i from 0 to n - 1 and swapping s[i] with s[n - 1 - i] swaps every pair twice, returning the list to its original order!
  • Off-by-one initialization (right = len(s)): Python lists are 0-indexed from 0 to len(s) - 1, so starting right at len(s) immediately raises IndexError on the first swap.
  • Overwriting s[left] before saving it: Writing s[left] = s[right] followed by s[right] = s[left] without temp (or without Python's simultaneous tuple assignment s[left], s[right] = s[right], s[left]) copies the right half over the left half and loses the original left characters.
  • Returning s instead of None: The type signature specifies -> None to emphasize in-place mutation; callers or tests checking reverse_string(s) is None will fail if you return s.

Alternative approaches

  • Single-index half loop: Loop for i in range(len(s) // 2): and swap s[i] with s[len(s) - 1 - i]. It performs the exact same swaps in O(n) time and O(1) extra space while computing the right index arithmetic on each iteration instead of decrementing right.
  • Production built-in (s.reverse()): In real Python code outside an algorithm interview, list.reverse() reverses the internal C pointer array in place in O(n) time and O(1) extra memory; the prompt bans it purely to test your two-pointer mechanics.

Follow-up questions

  • How would you adapt the two-pointer strategy to reverse the order of space-separated words inside a character list while keeping each word's letters forward? On a mutable list of characters (such as list("the sky is blue")), apply the same in-place two-pointer reversal helper twice: first reverse the entire array ("eulb si yks eht"), which puts the words in the right order with their letters backward, and then scan left-to-right to reverse each space-separated word slice [word_start .. word_end] back right-side up ("blue is sky the"). Every character is swapped at most twice, keeping total time O(n) and extra space O(1) (and if extra spaces must be trimmed, a third read/write two-pointer pass compacts them in place).

```python def reverse_slice(chars, left, right): while left < right: chars[left], chars[right] = chars[right], chars[left] left += 1 right -= 1

def reverse_words_in_place(chars): reverse_slice(chars, 0, len(chars) - 1) word_start = 0 for idx in range(len(chars) + 1): if idx == len(chars) or chars[idx] == " ": reverse_slice(chars, word_start, idx - 1) word_start = idx + 1 ```

  • Why does passing an immutable string object instead of a mutable character array make O(1) auxiliary memory impossible? In Python (as well as Java, Go, and JavaScript), an immutable string is a string object whose bytes cannot be modified after creation. Because you cannot mutate characters inside a str, reversing a string of length n must allocate a brand-new buffer of size n (O(n) extra memory is mathematically unavoidable). True O(1) auxiliary space is only possible when the input arrives in a mutable container such as list, bytearray, or a C/C++ char[] — and on real Unicode text beyond single-byte ASCII, naive unit-by-unit swapping would also corrupt multi-byte UTF-8 sequences or multi-codepoint emoji grapheme clusters.
  • If you rewrote this reversal recursively rather than with a loop, how much call-stack memory would it consume? A recursive helper helper(left, right) that stops when left >= right, swaps s[left] and s[right], and calls helper(left + 1, right - 1) performs the exact same swaps, yet each recursive call pushes a new activation frame onto the call stack (the memory region tracking active function calls) until depth reaches n // 2, consuming O(n) stack space and breaking the O(1) memory requirement. Because Python does not perform tail-call elimination (a compiler optimization that reuses the current stack frame for a final recursive call) and defaults to a recursion limit of 1,000, an input of n = 10^5 (50,000 frames) will also crash with RecursionError.

Follow-up questions

Similar questions

More Cargurus interview questions

All 2 Cargurus questions →