Javatpoint Logo
Javatpoint Logo

How to reverse a string using recursion in Java

Recursion in Java is a process where a function/method calls itself consistently. In the programming language, if a program permits us to call a method inside a similar method name, it is known as a recursive call. It makes the code minimal, yet it is challenging to comprehend. It is utilized to tackle a complex problem that can be broken into more modest monotonous issues. Utilizing recursion, we can take care of numerous mind-boggling issues like the factorial program, Fibonacci series, Towers of Hanoi etc.

Methodology:

  1. To start with, eliminate the first element/ character from the string and append that element/ character toward the finish of the string.
  2. Repeat the above step until the info string becomes null.

StringReverse.java

Output:

How to reverse a string using recursion in Java

Explanation:

In the above program, we have made a method named reverseString(). It parses our null or not. Assuming that the string is vacant, it returns the same string. We have utilized the accompanying two methods from the String class:

Time complexity: O(n^2)

O(n^2) because substr() has the time complexity of O(k) where k is the size of the brought string back. So for each recursive call, we are decreasing the size of the string by one, which prompts a series like (k-1)+(k-2)+… +1 = k*(k-1)/2 = O(k^2) = O(n^2)

Space complexity: O(n)

Where n is the size of the string.

Efficient Approach:

We can store each person in the recursive stack and afterwards can print while returning as displayed in the underneath code:

Output:

How to reverse a string using recursion in Java

Time complexity: O(n), where n is the size of the string

Space complexity: O(n), where n is the size of the string







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA