Last Updated: June 7, 2026
Reversing a string moves the last character to the front, the second-to-last to the second position, and so on, so "hello" becomes "olleh". Empty strings and single characters come back unchanged.
The recursive view splits the string into its first character and everything after it. The reverse of "hello" is the reverse of "ello" with 'h' at the end, because 'h' started at the front and must finish at the back. Reversing "ello" is the same problem on a shorter string, which is what makes this recursive.
The rule is reverse(s) = reverse(rest) + first, where rest is s without its first character and first is that character. The function calls itself to reverse rest, then appends the saved first character behind it.
The recursion stops at the base case: a string of length 0 or 1 reads the same forward and backward, so reverse(s) = s. Since each call removes one character, the string shrinks until it reaches the base case. The base case returns, and the saved first characters attach one by one as the calls unwind, each landing behind the reversed remainder.
s is 0 or 1, return s. This is the base case.s without its first character, followed by that first character.Input:
The first call is reverse("hello"), which sets aside 'h' and returns reverse("ello") + "h". That call sets aside 'e' and returns reverse("llo") + "e", and the chain continues to reverse("lo"), then reverse("o"). The string "o" has length 1, so the base case returns "o". Now the calls unwind: reverse("lo") returns "o" + "l" = "ol", reverse("llo") returns "ol" + "l" = "oll", reverse("ello") returns "oll" + "e" = "olle", and reverse("hello") returns "olle" + "h" = "olleh". Each first character that was set aside on the way down attached to the back on the way up.
n calls, and each one builds a new string by copying its growing suffix, which costs up to n work per call.n pending frames at once.Reversing in place avoids building a new string at every step. Put a pointer at each end of a character array, swap the two characters they point to, then move both pointers inward. When they meet in the middle, every character has been moved to its mirror position and the array holds the reversed string. This does a single pass with constant extra space, in contrast to the recursion that rebuilds the suffix repeatedly.
left to the first index and right to the last index.left is less than right, swap the characters at left and right, then increment left and decrement right.Input:
The array is h, e, l, l, o, with left at index 0 and right at index 4. Swapping gives o, e, l, l, h, and the pointers move to 1 and 3. Swapping the e and the second l gives o, l, l, e, h, and the pointers move to 2 and 2. Now left equals right, so the loop stops. The middle character l stayed in place, and the array reads "olleh", matching the recursive answer with only two swaps.