Problem overview
The function reverseString receives a string s and returns a new string with the same characters in reverse order. It must use recursion, and a built-in reverse is off limits. "stressed" becomes "desserts", "Room42" becomes "24mooR" (digits and capitals move like any other character), and the empty string stays empty. The string has at most 1,000 characters, and the statement asks for O(n) time.
Approach: swap the two ends, then reverse the middle
To reverse a string, put its last character first and its first character last, and reverse whatever sits between them. The middle is a shorter version of the same problem, which is the recursive idea. The recursion stops when the two ends meet or cross: one character in the middle stays where it is, and nothing is left when the ends have passed each other.
There is a Python obstacle. Strings are immutable, so s[0], s[-1] = s[-1], s[0] fails:
t = "abc"
t[0], t[2] = t[2], t[0]
TypeError: 'str' object does not support item assignment
So the lesson copies the characters into a list, which can change, swaps inside the list, and joins the list back into a string at the end. The recursive helper is given the list and two indexes, left and right, so no part of the list is ever copied.
Step by step
- Write the helper's
defline abovereverseString:reverseChars(self, chars, left, right). It reversescharsfrom indexleftto indexright, changing the list in place, so it returns nothing. - Base case. If
left >= right, return. When the ends meet, one character is left and it stays; when they cross, nothing is left. - Swap the ends with one tuple assignment:
chars[left], chars[right] = chars[right], chars[left]. Python builds the pair on the right first, so both old values are read before either place changes. No temporary variable is needed. - Recurse inward. Call
self.reverseChars(chars, left + 1, right - 1)with the same list. The two ends are done, and the characters between them are the same problem, shorter by two. - In
reverseString, create the list:chars = list(s). It holds one character per element. - Start the recursion with
self.reverseChars(chars, 0, len(chars) - 1). For an empty string the last index is -1, and the first call stops at the base case since 0 is greater than -1. - Return
"".join(chars), which glues the characters together with nothing between them.
The solution in Python
class Solution:
def reverseChars(self, chars, left, right):
if left >= right:
return
chars[left], chars[right] = chars[right], chars[left]
self.reverseChars(chars, left + 1, right - 1)
def reverseString(self, s: str) -> str:
chars = list(s)
self.reverseChars(chars, 0, len(chars) - 1)
return "".join(chars)
Watching it work
For "stressed" the list starts as s t r e s s e d. Printing the string after each swap shows the ends moving inward:
0 7 dtresses
1 6 deressts
2 5 desesrts
3 4 desserts
stop at 4 3
Each line gives the two indexes that were swapped and the string afterwards. After the swap at indexes 3 and 4 the call is made with left = 4 and right = 3, the ends have crossed, and the base case returns. With an odd length such as 3, the stop comes when left == right, with the middle character untouched.
Python details
list("Room42")gives['R', 'o', 'o', 'm', '4', '2'], one single-character string per element.- The helper returns
Noneand changes the list it was given. That is whyreverseStringmust keep the list in a variable and use it afterwards. - Python has shortcuts,
s[::-1]and"".join(reversed(s)). They are what the statement means by a built-in reverse, so the lesson doesn't use them.
Complexity
Each call swaps one pair and moves both ends inward, so there are about n / 2 calls: O(n) time. The list takes O(n) extra space, and the pending calls on the call stack take another O(n). A version that returns reverse(s[1:]) + s[0] copies the string again at every level and costs O(n²) time. Because the helper's depth is only about half the string, 1,000 characters need about 500 nested calls, within Python's default recursion limit of 1000.
Edge cases and common mistakes
- Empty string.
list("")is empty, the starting indexes are 0 and -1, and the base case returns at once. The result is"". - One character.
leftandrightare both 0, so the base case returns and the character is unchanged. - Using
left > rightas the base case. It still works, since swapping an element with itself does nothing, but it makes one extra call for odd lengths. - Swapping with two assignments. Writing
chars[left] = chars[right]and thenchars[right] = chars[left]sets both places to the same character, because the first line already overwrote the original value. - Forgetting to move the indexes. Passing
leftandrightunchanged never reaches the base case.
Testing
The lesson's examples give "desserts", "24mooR" and "". A palindrome such as "abba" must come back unchanged, and a single letter must too.
