Full answer
Problem
- Given a string
s, return it reversed. - Given a list of characters
chars, reverse it in place and use O(1) extra memory.
Example: "hello" gives "olleh"; ["a", "b", "c", "d"] becomes ["d", "c", "b", "a"].
Constraints: 0 <= len(s) <= 10^5.
Brute force
Build a new string by prepending each character: out = ch + out. Each prepend copies the whole string, so this is O(n^2). Building a list and joining it once is O(n).
Optimal approach
- Returning a new string: slicing
s[::-1]is O(n) time and O(n) space for the result. Python strings are immutable, so any reversal of a string makes a copy. - In place on a list:
lo = 0,hi = len - 1. Whilelo < hi, swapchars[lo]andchars[hi], then move both pointers inward.
Why it works
After k swaps, the first k and last k positions are already in their final places. The pointers meet in the middle after n / 2 swaps, and a middle character in an odd-length list stays where it is.
Unicode caution
A Python str is a sequence of code points. Some visible letters are several code points: in Hindi, "ते" is "त" followed by the vowel sign "े"; an emoji with a skin tone or a family emoji joins several code points. Reversing by code point detaches the marks. The test in the code shows that "नमस्ते"[::-1] gives "ेत्समन", which is not a readable reversal. Correct user-facing reversal needs grapheme cluster segmentation (for example the third-party regex module's \X pattern). In JavaScript, the same issue appears with split(''), which splits UTF-16 code units, and the old substr method is deprecated in favour of slice.
Complexity
Slicing: O(n) time, O(n) space. Two pointers: O(n) time, O(1) extra space.
Code
def reverse_string(s):
"""Reverse by code points using slicing. O(n) time, O(n) for the new string."""
return s[::-1]
def reverse_in_place(chars):
"""Reverse a list of characters in place with two pointers. O(1) extra space."""
lo, hi = 0, len(chars) - 1
while lo < hi:
chars[lo], chars[hi] = chars[hi], chars[lo]
lo += 1
hi -= 1
return chars
if __name__ == "__main__":
assert reverse_string("hello") == "olleh"
assert reverse_string("") == ""
assert reverse_string("a") == "a"
assert reverse_string("नमस्ते") == "ेत्समन" # code points, not visible letters
assert reverse_in_place(list("abcd")) == list("dcba")
assert reverse_in_place(list("abc")) == list("cba")
assert reverse_in_place([]) == []
print("all tests passed")Save as a12_reverse_string.py and run python3 a12_reverse_string.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty string, a single character, odd and even lengths, strings with spaces or punctuation (reversed like any character), and non-Latin scripts as described above.
Pattern
Two pointers from both ends moving inward. The same structure checks palindromes, reverses words in place and partitions arrays.
def reverse_string(s):
"""Reverse by code points using slicing. O(n) time, O(n) for the new string."""
return s[::-1]
def reverse_in_place(chars):
"""Reverse a list of characters in place with two pointers. O(1) extra space."""
lo, hi = 0, len(chars) - 1
while lo < hi:
chars[lo], chars[hi] = chars[hi], chars[lo]
lo += 1
hi -= 1
return chars
if __name__ == "__main__":
assert reverse_string("hello") == "olleh"
assert reverse_string("") == ""
assert reverse_string("a") == "a"
assert reverse_string("नमस्ते") == "ेत्समन" # code points, not visible letters
assert reverse_in_place(list("abcd")) == list("dcba")
assert reverse_in_place(list("abc")) == list("cba")
assert reverse_in_place([]) == []
print("all tests passed")Slicing for strings, two-pointer swap for lists. A test documents code-point reversal of Devanagari text.
Complexity
Time: O(n). Space: O(n) for a new string; O(1) extra for in-place list reversal. Repeated string concatenation in a loop is O(n^2) because strings are immutable.
By level
Fresher: Uses slicing and writes the two-pointer swap, and explains why strings cannot change in place in Python. Should test an empty string and a single character.
Mid: Explains the cost of repeated concatenation and the code point versus grapheme distinction with an example. Can explain why the two-pointer swap needs a list rather than a string in Python.
Senior: Discusses Unicode normalisation forms, grapheme segmentation libraries, UTF-16 surrogate pairs in other languages and how that affects APIs that reverse or truncate user text. Can say when reversing bytes instead of characters corrupts text.
Key points
- s[::-1] makes a reversed copy in O(n)
- In-place reversal swaps ends with two pointers
- Strings are immutable in Python, so reversal always copies
- Code points are not always visible characters
- Prepending in a loop is O(n^2)
Common mistakes
- Building the result with repeated prepending
- Claiming in-place reversal of a Python str
- Ignoring combining characters and emoji sequences
- Moving only one pointer or using lo <= hi and swapping the middle twice for no reason
Follow-ups
- How would you reverse the words in a sentence in place?
- How do you reverse by grapheme cluster?
- How would you reverse a string recursively, and what is the cost?
Tips
- Give the one-line answer, then the in-place version
- Mention string immutability
- Raise Unicode before the interviewer does
Evaluation rubric
- Correct reversal both ways
- Correct complexity including the immutability point
- Handles odd and even lengths
- Explains the Unicode limitation