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.

Overview

The problem, and the Python answer

Reverse a string. In Python the answer is one slice:

1Python
Output

That is idiomatic, C-speed, and correct. Stating it immediately is the right opening — and the interviewer is almost certainly asking something else underneath, so the useful part is what comes next.

The alternatives, and when each is relevant:

2Python
Output

The reason slicing wins: it allocates the result once and copies backwards in C. Building a string with += in a loop is O(n²), because strings are immutable and each concatenation copies everything so far.

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."

Reverse a string

Reverse a string. Now do it in place, with O(1) extra memory.

Run it

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.

3Python
Output
4Python
Output
5Python
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:

6Python
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":

7Python
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":

8Python
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", which 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.

What it is testing

Plain string reversal is a warm-up. What is being assessed:

Do you know the idiomatic one-liner, and can you also explain what it does?

Do you know that += in a loop is quadratic? This is the single most common Python performance mistake, and it is what the question is often probing for.

Do you understand immutability and therefore why "in place" is not available?

Do you clarify the requirement — characters or words?

Do you know that characters are not code points? The Unicode point separates a careful answer from a superficial one.

Recap in one screen

  • s[::-1] is the idiomatic answer: O(n) time, O(n) space, implemented in C.
  • Python strings are immutable, so in-place reversal is impossible — the two-pointer version needs a list.
  • Never build a reversed string with += in a loop; that is O(n²).
  • Clarify whether characters or words are to be reversed; split() with no argument handles whitespace correctly.
  • Slicing reverses code points, not grapheme clusters, so combining characters and emoji break.

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

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.

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.