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:
sis mutated to["t", "n", "a", "l", "p"](returnsNone) - Explanation: Outer indices
0("p") and4("t") trade places first, then indices1("l") and3("n") trade places. Index2("a") sits at the middle and stays put.
Example 2
- Input:
s = ["G", "r", "a", "p", "h", "7"] - Output:
sis mutated to["7", "h", "p", "a", "r", "G"](returnsNone) - 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 points32through126). - Auxiliary space must be
O(1)beyond the input list itself.
Step-by-step walkthrough
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 returnNone.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]insidereverse_string(s)only points the local variable namesat 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)is5or100,000. Built-in shortcuts likes.reverse(),reversed(s), slicing (s[::-1]), or copyingsinto a helper list are all off-limits.
- 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
Why the naive copy-and-overwrite approach breaks the space rule
If extra memory were free, the most direct idea would read
sbackward into a second list and copy the characters back intos: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 — butreversed_copystoresnelements at once (O(n)extra space). To drop extra space down toO(1), we need to rearrange characters directly insides.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 generalindex itrades places withindex 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
leftandrightthat move coordinately across an array — we only ever need three tiny variables (left,right, and a 1-charactertempslot for the swap):- Start
left = 0andright = len(s) - 1. - Swap
s[left]ands[right]usingtemp. - Advance
left += 1andright -= 1one 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 ofright(s[right + 1:]) is already in its final reversed position, whiles[left : right + 1]still needs to be reversed.- Start
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 index2(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),leftbecomes2andrightbecomes1(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 = 0andright = 0; forn = 0,left = 0andright = -1. In both casesleft < rightis immediatelyFalse, so the loop safely does zero swaps!
Keep
while left < right:as the condition. If you kept looping past the midpoint (for examplefor left in range(len(s)):), you would swap every pair a second time and undo the reversal!- Odd length (
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
nalways performs exactlyn // 2swaps (2swaps forn = 5,3swaps forn = 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):
- Start
left = 0("p") andright = 4("t"). Since0 < 4, swap them ->["t", "l", "a", "n", "p"], then move toleft = 1, right = 3. - At
left = 1("l") andright = 3("n"),1 < 3, so swap them ->["t", "n", "a", "l", "p"], then move toleft = 2, right = 2. - Now
left == right == 2:2 < 2isFalse, so the loop stops, leaving the middle"a"untouched in its exact final spot and returningNone.
Complexity
- Time: O(n), where
n = len(s). Each iteration movesleftup by1andrightdown by1, so the loop runs exactlyn // 2times and performs a constant-time (O(1)) swap and two integer updates per step. - Space: O(1) extra memory. Regardless of whether
shas1character or100,000characters, we allocate only two integer indices (left,right) and one temporary reference (temp).
Edge cases
- Single character (
["x"]):left = 0andright = 0, soleft < rightis immediatelyFalse; zero swaps run and["x"]stays unchanged. - Two characters (
["a", "b"]): Smallest even length — swaps(0, 1)once, thenleft = 1, right = 0crosses and stops cleanly. - Odd vs. even lengths: Odd lengths stop when
left == rightat the center element; even lengths stop whenleft == right + 1right after swapping the innermost pair. - Empty list (
[], outside the1 <= nconstraint):left = 0andright = -1, so0 < -1isFalseand the function safely returnsNonewithout raisingIndexError. - Palindromes, duplicate characters, and punctuation (
["r", "a", "c", "e", "c", "a", "r"],["!", " "]): Swapping identical characters or symbols works identically without needing any special-caseif s[left] != s[right]check.
Common mistakes
- Rebinding the parameter (
s = s[::-1]): Creates a new list and points only the local variablesto it; the caller's list is never modified. (Even slice assignments[:] = s[::-1]mutates the caller's list, but still allocates anO(n)temporary slice copy.) - Looping all the way to
n - 1: Iteratingifrom0ton - 1and swappings[i]withs[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 from0tolen(s) - 1, so startingrightatlen(s)immediately raisesIndexErroron the first swap. - Overwriting
s[left]before saving it: Writings[left] = s[right]followed bys[right] = s[left]withouttemp(or without Python's simultaneous tuple assignments[left], s[right] = s[right], s[left]) copies the right half over the left half and loses the original left characters. - Returning
sinstead ofNone: The type signature specifies-> Noneto emphasize in-place mutation; callers or tests checkingreverse_string(s) is Nonewill fail if youreturn s.
Alternative approaches
- Single-index half loop: Loop
for i in range(len(s) // 2):and swaps[i]withs[len(s) - 1 - i]. It performs the exact same swaps inO(n)time andO(1)extra space while computing the right index arithmetic on each iteration instead of decrementingright. - Production built-in (
s.reverse()): In real Python code outside an algorithm interview,list.reverse()reverses the internal C pointer array in place inO(n)time andO(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 timeO(n)and extra spaceO(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 lengthnmust allocate a brand-new buffer of sizen(O(n)extra memory is mathematically unavoidable). TrueO(1)auxiliary space is only possible when the input arrives in a mutable container such aslist,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 whenleft >= right, swapss[left]ands[right], and callshelper(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 reachesn // 2, consumingO(n)stack space and breaking theO(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 of1,000, an input ofn = 10^5(50,000frames) will also crash withRecursionError.
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?
- Why does passing an immutable string object instead of a mutable character array make O(1) auxiliary memory impossible?
- If you rewrote this reversal recursively rather than with a loop, how much call-stack memory would it consume?
Similar questions
- Binomial Coin-Bias Estimation and Overdispersion Diagnostics
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One