Approach: The solution traverses the string from the last character to the first character and appends each character to a result string. This manually constructs the reversed string without relying on any built-in reversal functionality.
This approach demonstrates a clear understanding of string manipulation and iteration, which is commonly evaluated in Java interviews.
Java Solution:
public class ReverseString {
public static String reverse(String input) {
String reversedString = "";
for (int index = input.length() - 1; index >= 0; index--) {
reversedString += input.charAt(index);
}
return reversedString;
}
public static void main(String[] args) {
String input = "Java";
String reversedString = reverse(input);
System.out.println("Original String: " + input);
System.out.println("Reversed String: " + reversedString);
}
}Output: Original String: Java Reversed String: avaJ
Time Complexity: O(n), where n is the length of the string since each character is processed exactly once.
Space Complexity: O(n), as a new string is created to store the reversed result.
Key Interview Points: • This solution avoids using built-in reversal methods such as StringBuilder.reverse(). • Using String concatenation inside a loop creates multiple intermediate String objects due to String immutability. • A more efficient production approach is to use a character array or StringBuilder for O(n) time with reduced object creation.