Start learning free

LESSON 389 OF 673 · RECURSION

Recursive String Reverse in Python: Swap the Ends, Recurse Inward

Practice O(n) Read the full explanation

You get a string s. Return a new string with the characters of s in reverse order.

Solve it with recursion, a function that calls itself. Don't use a built-in reverse. A loop would work too, but this lesson is about the recursive call.

The string can be empty. Its reverse is then empty too, shown as "".

 

Example 1:

Input: s = "stressed"
Output: "desserts"
Explanation: The last letter, d, now comes first.
The first letter, s, now comes last.

Example 2:

Input: s = "Room42"
Output: "24mooR"
Explanation: Digits and capital letters move like any other character.

Example 3:

Input: s = ""
Output: ""
Explanation: An empty string stays empty.

 

Constraints:

  • 0 to 1,000 characters.
  • Each character is an English letter or a digit.
Note:

Your solution should run in O(n) time, where n is the length of s.



Swap the first and the last character. The characters between them form a shorter string to reverse: the same problem.

Copy the characters into a list you can change. Give the recursive function two indexes, one for each end. When they meet or cross, nothing is left to swap.

Each call swaps two characters and moves both ends one step inward. That makes about n / 2 calls: O(n) time.
The characters and the calls waiting on the call stack take O(n) extra space.
Another way builds a new string at each call: the rest reversed, plus one character. It copies the characters again and again, which costs O(n2) time in most languages.
STEP 1 OF 7
    Ctrl + Enter to check

    PYTHON · RECURSION

    Recursive String Reverse in Python, explained

    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

    1. Write the helper's def line above reverseString: reverseChars(self, chars, left, right). It reverses chars from index left to index right, changing the list in place, so it returns nothing.
    2. Base case. If left >= right, return. When the ends meet, one character is left and it stays; when they cross, nothing is left.
    3. 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.
    4. 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.
    5. In reverseString, create the list: chars = list(s). It holds one character per element.
    6. 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.
    7. 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 None and changes the list it was given. That is why reverseString must 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. left and right are both 0, so the base case returns and the character is unchanged.
    • Using left > right as 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 then chars[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 left and right unchanged 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.

    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free