Search code examples
javatimecomplexity-theoryanalysis

How is the time complexity O(N^2) here?


I already know that the answer to this question is O(N^2) but I am not able to see how. I know the for loop runs N times, but how can it run N^2 times?

public static String rev(String s) {
    String r = "";
    int N = s.length();
    for (int i = 0; i < N; i++) {
        r = s.charAt(i) + r;
    }
    return r;
}

Solution

  • In Java, String concatenation r = s.charAt(i) + r in a loop is O(N^2), because Strings are immutable - a new copy of the String is created on each concatenation.