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
- Write the helper above
reverseString:reverseChars(chars []byte, left int, right int). It returns nothing. - 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. - 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. - 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. - In
reverseString, copy the string into bytes:chars := []byte(s). The conversion copies the data, sositself stays unchanged. - 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. - 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, aworks because Go reads the right-hand values first. Withx, y := 1, 2, the linex, y = y, xleavesxas 2 andyas 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 withstring(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[]runeinstead.
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".leftandrightare 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. Usingleft == rightalone 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
stringto 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".
