String Reversal Approaches in DSA Java - Time & Space Complexity
We want to understand how long it takes to reverse a string as the string gets longer.
How does the work grow when the input string size increases?
Analyze the time complexity of the following code snippet.
public String reverseString(String s) {
char[] chars = s.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);
}
This code reverses a string by swapping characters from the start and end moving towards the center.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Swapping characters inside a while loop.
- How many times: About half the length of the string (n/2 times).
As the string gets longer, the number of swaps grows roughly in half proportion to the string length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 5 swaps |
| 100 | 50 swaps |
| 1000 | 500 swaps |
Pattern observation: The operations grow linearly with input size, just half as many swaps as characters.
Time Complexity: O(n)
This means the time to reverse the string grows directly in proportion to the string length.
[X] Wrong: "Reversing a string takes constant time because we just swap characters."
[OK] Correct: Each character must be visited and swapped, so the time grows with string length, not fixed.
Understanding how string reversal scales helps you explain efficiency clearly in interviews and shows you can analyze simple loops well.
"What if we used recursion to reverse the string instead of a loop? How would the time complexity change?"
Practice
Solution
Step 1: Understand Java String reversal methods
Java'sStringclass does not have areverse()method, butStringBuilderdoes.Step 2: Identify correct usage of
Creating aStringBuilderStringBuilderfrom the string and callingreverse()thentoString()returns the reversed string.Final Answer:
Using new StringBuilder(str).reverse().toString() -> Option AQuick Check:
StringBuilder.reverse() = correct reversal [OK]
- Trying to call reverse() directly on String
- Using non-existent String.reverse() method
- Assuming toCharArray() has reverse() method
str using a for loop in Java?Solution
Step 1: Understand string indexing in Java
String indices start at 0 and go to length()-1.Step 2: Identify correct loop to reverse string
Loop from last index (length()-1) down to 0, appending characters to reversed string.Final Answer:
for (int i = str.length() - 1; i >= 0; i--) reversed += str.charAt(i); -> Option CQuick Check:
Loop from end to start = correct reversal [OK]
- Looping forward instead of backward
- Using 1-based indexing instead of 0-based
- Accessing charAt with index equal to length()
String str = "hello";
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i);
}
System.out.println(reversed);Solution
Step 1: Trace the for loop from end to start
The loop starts at index 4 ('o') and goes down to 0 ('h'), appending each character to reversed.Step 2: Build reversed string step-by-step
Characters appended in order: 'o', 'l', 'l', 'e', 'h' forming "olleh".Final Answer:
olleh -> Option BQuick Check:
Reverse of "hello" = "olleh" [OK]
- Expecting original string output
- Confusing loop direction
- Assuming syntax error due to += on strings
String str = "world";
String reversed = "";
for (int i = 0; i <= str.length(); i++) {
reversed += str.charAt(i);
}
System.out.println(reversed);Solution
Step 1: Check loop boundary conditions
The loop runs from i=0 to i=str.length() inclusive, but valid indices are 0 to str.length()-1.Step 2: Identify exception cause
Accessingstr.charAt(str.length())causes IndexOutOfBoundsException.Final Answer:
Loop condition should be i < str.length() to avoid IndexOutOfBoundsException -> Option DQuick Check:
Index must be less than length() [OK]
- Using <= instead of < in loop condition
- Ignoring exception from invalid index
- Assuming StringBuilder is mandatory
str, which approach efficiently reverses it without using extra space for another string in Java?Solution
Step 1: Understand in-place reversal concept
Strings in Java are immutable, so we cannot change them directly, but char arrays can be modified in place.Step 2: Use char array swapping to reverse without extra string
Convert string to char array, swap characters from start and end moving inward, then create string from modified array.Step 3: Compare with other options
Other methods create new strings or use extra space, so not in-place.Final Answer:
Convert to char array, swap characters from ends moving inward, then create new string -> Option AQuick Check:
In-place reversal uses char array swaps [OK]
- Assuming StringBuilder.reverse() is in-place
- Using string concatenation causing extra space
- Ignoring string immutability in Java
Ready to prove it?
Pass the test and this pattern moves unknown
