Q1: How do you reverse a String in-place without built-in reverse functions?
Strings in Java are immutable, so to reverse a String in-place, convert it to a char[] array and use the Two-Pointer Technique. Initialize pointers at both ends of the array, swap characters, and move the pointers toward the center until they meet.
Two-Pointer String Reversal
public class StringReversal {
public static String reverse(String input) {
if (input == null || input.length() <= 1) return input;
char[] chars = input.toCharArray();
int left = 0, right = chars.length - 1;
while (left < right) {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
return new String(chars);
}
}💡 Swaps characters from outside inward until the pointers cross.
Key Takeaways
- Strings are immutable in Java; convert to
char[]for swapping. - Two-pointer technique yields $O(n)$ time and $O(n)$ space complexity.
Knowledge Check
What is the time complexity of reversing a string of length N using the two-pointer approach on a char array?