DEV Community

Md. Mohaiminul Islam
Md. Mohaiminul Islam

Posted on

Reverse a string using a recursive function

Reversing a string without using built-in functions is a common interview question. Let's explore this problem using recursive approach. I will discuss a common approach and an approach similar to the iterative approach using loop.

First, the common solution uses slice operation to remove the last or first character in a string in each recursive call and concatenating those returns to form the reverse string. The base case for this approach is when the string is reduced to an empty string.

const reverseString = str => {

  if (str === '') {
    return "" ;
  }

  return reverseString(str.slice(1)) + str[0] ;
}
Enter fullscreen mode Exit fullscreen mode

This solution has time complexity of O(n). The function is recursively called n times and every time before a recursive call there is a slice method call which takes O(1) time for strings in the runtimes using v8 engine. (check this discussion for explanation by a v8 developer Link)
But the time complexity of slice can change the time complexity of this solution to O(n^2) depending on slice's implementation in different languages or browser runtime.

In my second approach we can use an index parameter with default value of 0. Index will be incremented by 1 in each recursive call and the character at that index will be concatenated at the end to get the reversed string. The base case for this approach is index being equal to the string length.

const reverseString2 = (str, index = 0) => {

  if (index === str.length) {
    return '';
  }

  return reverseString2(str, index + 1) + str[index];
}
Enter fullscreen mode Exit fullscreen mode

This approach has time complexity of O(n). It uses index traversal to concatenate the reversed string similar to the iterative solution using loop. It eliminates the need of slice method used in the previous approach.

(Let me know in the comments if you have any questions or corrections to add.)

Top comments (0)