Problem Statement
Write a program to reverse a string. Explain both iterative and recursive methods.
Explanation
To reverse a string iteratively, use two pointers from start and end, swapping characters until they meet. Recursively, reverse the substring excluding the first character and append the first character at the end. Both approaches have O(n) time complexity. Iterative uses O(1) space, recursive uses O(n) stack space.
Code Solution
SolutionRead Only
// Iterative
String reverse(String s){
char[] arr=s.toCharArray();
int i=0,j=arr.length-1;
while(i<j){ char t=arr[i]; arr[i]=arr[j]; arr[j]=t; i++; j--; }
return new String(arr); }
// Recursive
String revRec(String s){ if(s.length()<=1) return s;
return revRec(s.substring(1))+s.charAt(0); }Practice Sets
This question appears in the following practice sets:
