Reverting a mutable string implies relocating at least half of the characters (if you do it in-place), so that is O(n) complexity. The code you posted has two loops, confirming it's O(n).

On a more thoeretical note, the entire StringBuilder implementation could be devoted to O(1) inversion, such that you only set a flag and then all the methods honor it by interpreting the array contents either front-to-back or back-to-front. I say "theoretical" because there's no point in increasing the complexity of everything, making it slower as well, just to have O(1) string inversion.

Answer from Marko Topolnik on Stack Overflow
🌐
Medium
medium.com › @AlexanderObregon › javas-stringbuilder-reverse-method-explained-b2b701ee2029
Java’s StringBuilder.reverse() Method Explained | Medium
October 3, 2024 - This technique is highly efficient because it only requires traversing the string once and swapping characters, resulting in a time complexity of O(n), where n is the length of the string.
🌐
Reddit
reddit.com › r/algorithms › what is the time complexity of reversing a string?
r/algorithms on Reddit: What is the time complexity of reversing a string?
October 23, 2020 -

I'm getting ready for an interview and practicing time complexity and I'm ok at recognizing the complexity for the code I've written myself but have a harder time when I throw in methods from the java library.

For example, I read that the method concat was similar to += and that concat time complexity was O(n^2). So if I reverse a string with the code below does that mean my time complexity is O(n^2)? With a space complexity of O(n) since? Where n is the length of the string.

String str="hello"
String s="";
for(int i =str.length()-1; i>=0;i--){
s+=str.substring(i,i+1);
}

With this code is the space complexity O(n) and the time complexity O(n)? Where n is the length of the string.

String str="hello";
char[] cArr = str.toCharArray();
int i =0;
int j = cArr.length-1;
char temp;
while(i<j){
    temp =cArr[i];
    cArr[i]=cArr[j];
    cArr[j]=temp;
    i++;
    j--;
}
str=String.valueOf(cArr);
Top answer
1 of 5
17
It should be simply O(n) where n is the length of string. If you think of a string as an array, you simply swap characters between left and right ends until they cross over the mid-point — which means O(n/2) and simplified to O(n).
2 of 5
8
I don't know the time complexity of internal java lib functions by heart- I'll leave it to someone else to comment on that. What I do want to offer is a technique to sanity check your understanding. Asymptotic time complexity is very much on the numerical / theoretical side of things, but the actual computation time will reflect this behavior once the input size grows large enough. What you can do is repeatedly time the function on various input sizes spanning many orders of magnitude until you reach some limit (probably where the computation starts taking multiple seconds). You can then graph input size vs computation time, and see if its constant, linear, quadratic, logarithmic, etc., by eye. If you want a more precise measurement, take the log of both the input sizes and the computation times (so its a log-log plot), and a best-fit line through your data points (using a linear regression), the slope is the exponent of your variable in your measured time complexity (so a slope of 2 corresponds to observed quadratic time behavior). This isn't perfect, there can easily be huge constants throwing off your measured time complexity, you'll likely drop any logarithmic factors, etc. Its more of a coarse sanity check- if you think the algorithm is O(N2 ) but you experiment and see a near-straight line, and the log-log plot has a slope of 1, then you can reason that its likely not quadratic, its behaving more as a linear-time algorithm, and you should recheck your calculations.
🌐
Blogger
javarevisited.blogspot.com › 2016 › 03 › how-to-reverse-string-in-place-in-java.html
How to Reverse a String in place in Java - Example
The time complexity of this algorithm is O(n/2)I mean O(n) where n is the length of String. Ideally, whenever you need to reverse a String in your application, you should be using the reverse() method of StringBuilder.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › reverse-a-string
Reverse a String – Complete Tutorial - GeeksforGeeks
// Function to reverse a string ... Output · efcdba · Time Complexity: O(n) Auxiliary Space: O(1) in C++ and python and O(n) in Java, C# and JavaScript (extra space is used to store in array or list or StringBuilder for ...
Published   October 3, 2025
🌐
Coderanch
coderanch.com › t › 545713 › java › string-reverse
string reverse O(N) or O(N/2) (Java in General forum at Coderanch)
I think we cant reduce the string reverse to O(N/2)? Please correct me if i am wrong. Thanks Chandrashekar ... Note that there is no O(N/2) - it is linear complexity, and asymptotically the same as O(N). In this particular case, performance is probably improved much more by using a StringBuilder instead of string concatenation. ... Hi, In java String is stored as a char array; in java size of the array is predetermined and stored in head so getting the size of the array or string will be O(1).
🌐
Java67
java67.com › 2016 › 06 › how-to-reverse-string-in-place-in-java.html
[Solved] How to reverse a String in place in Java? Example | Java67
The time complexity of this algorithm is O(n/2) + time taken in swapping, which effectively adds up to O(n) time. This means time will increase in the proportion of the length of String or the number of characters on it.
Top answer
1 of 1
2

Linear in space

Both are linear in space.

The first one is linear because the StringBuilder makes a copy of the string.

The second one is linear because toCharArray makes a copy of the string. We know it can't use the backing array of the string, because the string is immutable. Clearly you can modify the character array. We can ignore the swap variable (c), as it is either constant space or

We can consider a Java compiler (even if none currently work this way) that would release the backing array to the toCharArray, but we can't guarantee that. Because the calling code may want to use the string after calling this method. So the assumption in the method is that we are creating a new array.

If the input is a string and the output is a different string (and we can't change the original string, so it has to be different), then linear time is the best we could possibly do. So even without the intermediate variable, these would still be linear in space. Both create new strings.

Linear in time

Both are linear in time.

The first one does \$n\$ iterations with one append operation per iteration. The append operations should be constant time. There may be occasional copy operations that can be amortized to be constant time per append operation or linear time overall. That's \$\mathcal{O}(n)\$.

The second one does \$\frac{n}{2}\$ iterations with two array assignments per iteration. That's also linear, \$\mathcal{O}(n)\$. Because \$\frac{n}{2}\$ grows linearly with \$n\$ and two is a constant.

Constant space

To have a method be constant in space, it needs to return the same memory that brings the input. E.g.

public void reverse(char[] chars) {
    for (int i = 0, j = chars.length - 1; i < j; i++, j--) {
        char temp = chars[i];
        chars[i] = chars[j];
        chars[j] = temp;
    }
}

This is constant in space and linear in time. But it neither takes nor returns a string.

Constant space and time

There's a sort of backwards way of reversing a string in constant time and space.

class ReversedString {

    private String string;

    public ReversedString(String string) {
        this.string = string;
    }

    public char charAt(int index) {
        return string.charAt(string.length() - 1 - index);
    }

}

But we wouldn't be able to just use this as a string without creating a new string. The only operation that works (so far) is charAt. We might be able to make other operations work, but not all of them. In particular, a toString would be linear in time and space, just like the original methods. Because it would have to make a new string of the same length.

Find elsewhere
🌐
GitHub
github.com › rootusercop › TimeComplexityOfPredefinedMethodsInJava › blob › master › String, StringBuilder and StringBuffer class methods
TimeComplexityOfPredefinedMethodsInJava/String, StringBuilder and StringBuffer class methods at master · rootusercop/TimeComplexityOfPredefinedMethodsInJava
PLEASE NOTE THAT reverse() method is NOT PRESENT in String class of JAVA. The reason being String class · in JAVA is immutable. However, for some reason substring() method is present in String class even though String · is immutable in JAVA. Also StringBuilder and StringBuffer classes each have substring() method. · Source: http://stackoverflow.com/questions/19814067/time-complexity-of-stringbuilder-reverse-method ·
Author   rootusercop
🌐
Medium
medium.com › @techie_arbaaz › 10-common-coding-interview-questions-on-string-using-java-4a19fc4d9ce8
Common Coding Interview Questions on String using Java | by Techie Arbaaz | Medium
August 14, 2025 - public class ReverseString { public ... sb.append(str.charAt(i)); } System.out.println("Reversed String: " + reversed); } Time Complexity: O(n) The reverse() method iterates through the StringBuilder to reverse the string....
🌐
GeeksforGeeks
geeksforgeeks.org › java › stringbuilder-reverse-in-java-with-examples
StringBuilder reverse() in Java with Examples - GeeksforGeeks
October 18, 2018 - The reverse method of the StringBuilder class is used to reverse the sequence of characters in a StringBuilder object.
🌐
IncludeHelp
includehelp.com › java › stringbuilder-reverse-method-with-example.aspx
Java StringBuilder reverse() method with example
reverse() method does not throw an exception at the time of reversing this character sequence. ... It does not accept any parameter. ... The return type of this method is StringBuilder, it returns a reference to this StringBuilder object. ... // Java program to demonstrate the example // of StringBuilder reverse() method of StringBuilder public class Reverse { public static void main(String[] args) { // Creating an StringBuilder object StringBuilder st_b = new StringBuilder("Java World "); // Display st_b System.out.println("st_b = " + st_b); // By using reverse() method is to reverse the characters // of this st_b object st_b.reverse(); // Display reversible st_b System.out.println("st_b.reverse() = " + st_b); } }
🌐
Stack Overflow
stackoverflow.com › questions › 55252335 › java-string-manipulation-time-and-space-complexity-using-stringbuilder
Java String manipulation: Time and Space complexity using StringBuilder - Stack Overflow
Below is my code (Programming language used - Java): public String reverseWords(String s) { StringBuilder sb = new StringBuilder(); s += ' '; for (int i = 1; i < s.length(); i++) { if (s.charAt(i) == ' ' && s.charAt(i-1) != ' ') { if (sb.length()>0) sb.append(' '); for (int j = i-1; j >= 0 && s.charAt(j) != ' '; j--) sb.append(s.charAt(j)); } } return sb.toString(); } Interviewer then asked with Time and Space complexity of the code to which I said: Space complexity looks O(N) (where N is number of characters in input) and Time complexity is Quadratic.
🌐
GeeksforGeeks
geeksforgeeks.org › java › reverse-a-string-in-java
Reverse a String in Java - GeeksforGeeks
Explanation: StringBuilder objects are mutable, and their reverse() method reverses the content in-place, which is faster than manual looping. We can use character array to reverse a string. Follow Steps mentioned below: First, convert String to character array by using the built-in Java String class method toCharArray().
Published   October 14, 2025
🌐
CodeGym
codegym.cc › java blog › random › different ways to reverse a string in java
Different Ways to Reverse a String in Java
February 1, 2023 - The time complexity of the above code is O(N), and as we have iterated over all the n elements the space complexity of the above code is O(N). Now let us read about the next process which is reversing the string using the string builder, so now let us read about it in detail: We can also reverse the string in Java by using the StringBuilder class.
🌐
Coderanch
coderanch.com › t › 472416 › java › Timing-complexity-string-reverse
Timing complexity of this string reverse (Java in General forum at Coderanch)
Jacob Sonia wrote: Please help me what would be the exact timing complexity of this program....i would think it should be 2n - 2 No it's far worse, Because String is mutable it will rather be quadratic, like O(n*n). But you're lucky. Most Java compilers will replace the rstr String with a ...
🌐
Scaler
scaler.com › home › topics › reverse a string in java
Reverse a String in Java - Scaler Topics
March 14, 2024 - After the loop completes, the result string will be the reversed version of the input string. ... This method is simple and intuitive, but it's worth noting that string concatenation in a loop like this can be inefficient for very long strings due to the way strings are handled in Java. Each concatenation creates a new string object, so for more performance-critical applications or large strings, using a StringBuilder or a similar approach might be more suitable.
🌐
Tutorialspoint
tutorialspoint.com › home › java/lang › stringbuilder reverse method in java
StringBuilder reverse Method in Java
September 1, 2008 - Learn how to use the StringBuilder reverse method in Java to reverse strings efficiently. Explore examples and best practices.