Reverse a String in place
This is a common interview question for junior developers. We need to reverse a String without creating another string or array.
Reverse a String in place - implementation in Java
It first converts String to StringBuilder, so we can mutate the contents without creating temporary String objects.
Then, it goes through StringBuilder and swaps characters from both ends until it reaches the midpoint. At that point, String is reversed, without any additional memory i.e. in place.
Then, it goes through StringBuilder and swaps characters from both ends until it reaches the midpoint. At that point, String is reversed, without any additional memory i.e. in place.
public class Main {
public static void main(String[] args) {
System.out.println(reverse("Hello"));
}
private static String reverse(String str) {
StringBuilder builder = new StringBuilder(str);
builder.reverse();
for (int i = 0; i < str.length() / 2; i++) {
char leftSide = str.charAt(i);
char rightSide = str.charAt(str.length() - 1 - i);
// swap leftSide and rightSide
builder.setCharAt(i, rightSide);
builder.setCharAt(str.length() - 1 - i, leftSide);
}
return builder.toString();
}
} Output: olleH
Here, we are not creating new String objects, instead just swapping characters in the StringBuilder.
Note: We could also simply use a builder.reverse() method, but it creates an array of bytes in the background and we need this solution to be in place.
The time complexity of this solution is O(n/2) or just O(n).
Space complexity is O(1).
Space complexity is O(1).
No comments:
Post a Comment