Start learning free

LESSON 105 OF 314 · RECURSION

Recursive String Reverse in Go: 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 an array 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

    GO · RECURSION

    Recursive String Reverse in Go, explained

    Problem overview

    The function reverseString receives a string s and returns a new string with the same characters in reverse order. The lesson wants a recursive solution and no built-in reverse. The string can be empty, and its reverse is empty too. The characters are English letters and digits, and there are at most 1,000 of them.

    "stressed" becomes "desserts", and "Room42" becomes "24mooR": digits and capital letters move like any other character. An empty string stays empty. The solution must run in O(n) time.

    Approach: swap the ends, then reverse the middle

    To reverse a sequence, swap its first and last items, then reverse what lies between them. The part in the middle is the same problem on a shorter sequence. The base case is a part with at most one item: nothing needs to move.

    Go strings are immutable, so the swaps can't happen inside s. The plan is to copy the characters into a slice that can change, reverse that slice in place, and turn it back into a string. The recursive helper reverseChars takes the slice and two indexes, left and right, and reverses the part from left to right. A slice shares its bytes with the caller, so the swaps inside the helper change the caller's slice, and the helper needs no return value.

    The alternative is to return "the reverse of the rest, plus the first character" at each call. That builds a new string at every step and copies the characters again and again, which costs O(n*n) in total. Swapping in place avoids that.

    Step by step

    1. Write the helper above reverseString: reverseChars(chars []byte, left int, right int). It returns nothing.
    2. Base case: if left >= right, return. When the two indexes meet, one character is left in the middle and it stays where it is. When they cross, nothing is left. Without this check the calls would never stop.
    3. Swap the ends in one assignment: chars[left], chars[right] = chars[right], chars[left]. Go evaluates both sides' values before assigning, so no temporary variable is needed.
    4. Recurse on the inside: reverseChars(chars, left+1, right-1). For "stressed" the calls swap s and d, then t and e, then r and s, then e and s. After that the indexes have crossed and the base case stops.
    5. In reverseString, copy the string into bytes: chars := []byte(s). The conversion copies the data, so s itself stays unchanged.
    6. Call reverseChars(chars, 0, len(chars)-1). For an empty string, the last index is -1, so 0 is greater than -1 and the first call stops at the base case.
    7. Return string(chars), which builds a string from the bytes.

    The solution in Go

    func reverseChars(chars []byte, left int, right int) {
        if left >= right {
            return
        }
        chars[left], chars[right] = chars[right], chars[left]
        reverseChars(chars, left+1, right-1)
    }
    
    func reverseString(s string) string {
        chars := []byte(s)
        reverseChars(chars, 0, len(chars)-1)
        return string(chars)
    }

    Go details to notice:

    • Tuple assignment swaps. a, b = b, a works because Go reads the right-hand values first. With x, y := 1, 2, the line x, y = y, x leaves x as 2 and y as 1.
    • Strings are immutable, byte slices are not. You can't write s[0] = 'x'. Converting with []byte(s) makes a mutable copy, and converting back with string(chars) copies once more.
    • The helper changes the caller's slice. Slices are small headers pointing to shared memory, so no pointer or return value is needed.
    • Bytes versus characters. For letters and digits, one character is one byte, which is all this lesson uses. A character outside ASCII takes several bytes in UTF-8, and reversing bytes would break it: reverseString("é") returns a string of two bytes in the wrong order, which prints as "\xa9\xc3". To reverse arbitrary text, work on a []rune instead.

    Tracing "stressed"

    Each call swaps one pair, and the slice changes like this: after indexes 0 and 7 it is dtresses, after 1 and 6 it is deressts, after 2 and 5 it is desesrts, after 3 and 4 it is desserts. The next call has left 4 and right 3, so it returns.

    Complexity

    Time is O(n): about n / 2 calls, each doing a swap. Space is O(n): the byte slice holds n bytes, and the recursion goes about n / 2 calls deep, each waiting on the next. With at most 1,000 characters, 500 nested calls are fine.

    Edge cases and common mistakes

    • Empty string. It returns an empty string, since the base case fires immediately.
    • One character. "a" stays "a". left and right are both 0, so the base case returns.
    • Even and odd lengths. With an even length the indexes cross; with an odd length they meet in the middle. Both stop at left >= right. Using left == right alone would fail on even lengths and recurse forever (or until the indexes go out of range).
    • Not moving both indexes. Moving only one of them swaps the wrong pairs.
    • Expecting the original to change. []byte(s) copies, so after the call the original string still holds "stressed" while the result is "desserts".
    • Passing string to the helper. A string can't be swapped in place. The helper needs a slice.

    Testing

    Results from running the solution: "stressed" gives "desserts", "Room42" gives "24mooR", "" gives "", "a" gives "a", "ab" gives "ba" and "abc" gives "cba".

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