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;
}
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.