Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The time complexity for a code segment

From an online notes, I read the following java code snippet for reversing a string, which is claimed to have quadratic time complexity. It seems to me that the “for” loop for i just iterates the whole length of s. How does it cause a quadratic time complexity?

public static String reverse(String s)
{
  String rev = new String();
  for (int i = (s.length()-1); i>=0; i--) {
      rev = rev.append(s.charAt(i));
  }
  return rev.toString();
}
like image 714
user297850 Avatar asked Mar 15 '26 23:03

user297850


2 Answers

public static String reverse(String s)
{
  String rev = " ";
  for (int i=s.length()-1; i>=0; i--)
  rev.append(s.charAt(i); // <--------- This is O(n)
  Return rev.toString();
}

I copy pasted your code. I'm not sure where you get this but actually String doesn't have append method. Maybe rev is a StringBuilder or another Appendable.

like image 158
user802421 Avatar answered Mar 17 '26 12:03

user802421


Possibly because the append call does not execute in constant time. If it's linear with the length of the string, that would explain it.

like image 32
mwigdahl Avatar answered Mar 17 '26 12:03

mwigdahl