Reverse a string

s[::-1] is the idiomatic answer and allocates a full copy. The follow-up is always "now in place", which strings cannot do — so you convert to a list and run two pointers inwards, swapping as they go: n/2 swaps and O(1) extra memory.

StringsCoding problemEasy

Step through it

What to watch

  • The two pointers move towards each other and stop when they meet.
  • An odd-length string leaves the middle character alone — correct, not a bug.
  • Nothing is allocated: the same list is being rearranged.

Say this out loud

"s[::-1] in Python, but that's O(n) space. In place you'd take a character array and swap from both ends inwards until the pointers meet - n/2 swaps, O(1) extra."

Overview

Reversing a sequence swaps its ends and moves inward. Python strings are immutable, so an in-place version needs a mutable character array; if a new string is allowed, slicing is concise but uses O(n) extra space.

In this guide
  1. Run it: Reverse a string in code
  2. Reversing in place, and why Python cannot
  3. The variations that are actually asked
  4. The Python answer, and why it is not the whole answer
  5. The two-pointer version
  6. The variations that follow
  7. The Unicode problem
  8. Complexity and edge cases
  9. The follow-ups
  10. Sources and next steps

Run it: Reverse a string in code

Three reversals of the same text — the slice, the two-pointer swap, and the word-level variant — with the extra memory each one uses printed beside it.

1Python
Output
2Python
Output
3Python
Output

Reversing in place, and why Python cannot

The classic version of this question is "reverse a string in place with O(1) extra space", using two pointers:

4Python
Output

This cannot be done on a Python string, because strings are immutable. There is no way to modify one, so O(1) space is impossible. The reversed string is a new object.

That is worth saying explicitly rather than pretending otherwise. The in-place version applies to a list of characters, or to a mutable string type in another language.

The two-pointer loop is the answer being looked for in the general form: swap the ends, move inwards, stop when they meet. O(n) time, O(1) extra space, n/2 swaps.

The variations that are actually asked

Plain reversal is too simple to be the real question. Three variants are common:

Reverse the words, not the characters. "the sky is blue" → "blue is sky the":

5Python
Output

split() with no argument collapses runs of whitespace and discards empties, which handles " hello world " correctly. split(" ") does not.

Reverse each word in place, keeping word order. "the sky" → "eht yks":

6Python
Output

Reverse only the vowels, or only the letters, leaving other characters in position. A two-pointer scan that skips characters not to be moved.

Asking "reverse the characters or the words?" before starting is the right move; the question is frequently stated ambiguously on purpose.

The Python answer, and why it is not the whole answer

s[::-1] is correct, fast and what you should write in real code. It also allocates a second string of the same length, because Python strings are immutable and there is no in-place option. An interviewer asking for O(1) space is asking you to leave strings behind and work on a character array.

The two-pointer version

Put one pointer at each end. Swap the characters they name, move both inwards, stop when they meet. That is n/2 swaps and two integers of extra memory, regardless of length.

The loop condition is while lo < hi, strictly less than. With <= an odd-length string swaps its middle character with itself — harmless but pointless. And the condition is the part interviewers check.

The variations that follow

"Reverse the words but not the characters" — " ".join(s.split()[::-1]), or reverse the whole thing and then reverse each word in place, which is the O(1)-space trick.

"Reverse only the vowels" — the same two pointers, each skipping forward until it lands on a vowel. "Reverse in groups of k" — the same swap loop applied to each block.

The Unicode problem

s[::-1] reverses code points, and that is not always what a human means by reversing text.

Combining characters. "é" written as "e" plus a combining acute accent reverses into the accent followed by the "e". This renders as a different (and broken) sequence.

Emoji with modifiers. A skin-tone emoji is a base character plus a modifier, and reversing separates them.

Emoji sequences joined with zero-width joiners — family and profession emoji — break apart entirely.

The correct unit is the grapheme cluster: what a reader perceives as one character. Python's standard library has no grapheme segmentation, and the regex module does:

import regex
def reverse_graphemes(s):
    return "".join(reversed(regex.findall(r"\X", s)))

For ASCII text s[::-1] is fine. Raising this distinction shows you know the difference between bytes, code points and characters. And that difference is what several other interview questions in this area are actually about.

Complexity and edge cases

ApproachTimeSpace
s[::-1]O(n)O(n) — a new string
"".join(reversed(s))O(n)O(n)
Two pointers on a listO(n)O(1) extra
+= in a loopO(n²)O(n)
Edge caseBehaviour
Empty stringReturns empty
Single characterReturns itself
PalindromeReturns an equal string
WhitespacePreserved and reversed with everything else
NoneRaises — guard if the contract allows it

The follow-ups

"Do it without slicing." "".join(reversed(s)), or an explicit loop appending to a list and joining.

"Reverse in place." Only possible on a mutable sequence; explain why a Python string cannot be, then give the two-pointer version for a list.

"Reverse a linked list." A different and more substantial problem — three pointers, redirecting each next backwards. Frequently the real destination of this line of questioning.

"Check whether a string is a palindrome." Comparing s == s[::-1] works and allocates; two pointers from both ends is O(1) space and short-circuits on the first mismatch.

"Reverse only part of the string." Two pointers bounded by the given range.

Sources and next steps

How the code works

Three reversals of the same text — the slice, the two-pointer swap, and the word-level variant — with the extra memory each one uses printed beside it.

How the code works

  1. while lo < hi:Strictly less than. With <= an odd-length string swaps its middle character with itself — harmless, and the kind of detail the question exists to check.
  2. chars[lo], chars[hi] = chars[hi], chars[lo]Python evaluates the right side first, so this is a real swap. In most languages it needs a temporary, and forgetting it overwrites one of the two values.
  3. chars = list(s)The concession immutability forces. There is no in-place reversal of a str; "in place" means in a character array.
  4. while lo < hi and chars[lo] not in vowels:The inner skips need the lo < hi guard too, or a string with no vowels runs a pointer off the end. Nested pointer loops are where index errors hide.

Change one thing

  • Change the loop to while lo <= hi and print the swap count for an odd-length string. One wasted swap, same output.
  • Reverse the words with O(1) extra space: reverse the whole array, then reverse each word in place. That is the real interview follow-up.

Where this runs

Real CPython, compiled to WebAssembly and running on your own machine — nothing is uploaded. The first run takes a few seconds while the interpreter downloads; after that it is immediate. Need more room, or want to paste your own attempt? Use the Python compiler.

Check yourself

0 of 3

Answer without scrolling back up.

  1. Why can't you reverse a Python string in place?

  2. The two-pointer reversal loop uses `while lo < hi` rather than `<=` because:

  3. How many swaps does the in-place reversal make for n characters?

Cheat sheet

Reverse a string

Reverse a string with slicing, then do it in place on a character list with O(1) extra memory. Compare both approaches step by step.

INTERVIEW · vizlearn.in/interview/reverse-a-string.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.

Teaching a course with this? Individual teachers can use it freely; for a whole department or programme, see institutional licences.