What's the most efficient way to print a string backwards using recursion in java? If youre given this header:
public void printBackwards(String s)
What's the most efficient way to print a string backwards using recursion in java? If youre given this header:
public void printBackwards(String s)
Efficiency-wise the most efficient way is to not use recursion.
The iterative approach (loop-backwards over the string and print the characters) is linear, O(N), where N is the length of the string.
Since you ask about the recursive solution, though, it is quadratic, O(N^2) for time-complexity since N characters are printed and N substrings are made for each function call. (N-1 characters are copied into memory each time).
public void printBackwards(String s) {
if (!s.isEmpty()) {
int endPos = s.length() - 1;
System.out.print(s.charAt(endPos));
printBackwards(s.substring(0, endPos));
}
}
Since you want recursion, I'll give you a hint (as this is a question in your class):
Print the last character first. How would you print it forwards recursively? Now just go backwards!
Hover to reveal code :)
public void printBackwards(String s) {
if (s.length() == 0) return;
System.out.print(s.charAt(s.length() - 1);
printBackwards(s.substring(0, s.length() - 1);
}
The most efficient way using recursion is like this:
static void printBackwards(String s)
{
printBackwards(s, 0, s.length());
System.out.println();
}
static void printBackwards(String s, int start, int end)
{
if ((end-start)<2)
{
if (end>start)
{
System.out.print(s.charAt(start));
}
return;
}
int mid = start + (end-start)/2;
printBackwards(s, mid, end);
printBackwards(s, start, mid);
}
This is more efficient than the other answer, because it doesn't allocate a whole bunch of new strings and only uses O(log N) stack...
But, really you don't need recursion to print a string backwards.
NOTE: If this is homework and you hand this in, your prof will probably know that you didn't write it :)