Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String time complexity

public String joinWords(String[] words)
{ 
     String sentence = "";
     for (String w : words)
     {
        sentence = sentence + w;  
     }
     return sentence;
}

Assume that the strings are all the same length (call this x) and that there are n strings. On each concatenation,a new copy of the string is created, and the two strings are copied over,character by character. The 1st iteration requires us to copy x characters. The second iteration requires copying 2x characters. The third iteration requires 3x ,and so on. The total time therefore is O(x + 2x + . . . + nx). This reduces to O(xn^2).

1) I can't understand from the book answer how they get 3x characters in the third iteration , 4x in the 4th iteration . String is immutable and in each sentence variable assignment new String object is created . And then is should copy the previous value of the string char by char and the value of w . And i get 2x characters again . Thank you all !

like image 377
Vasili Anoshin Avatar asked Sep 17 '26 11:09

Vasili Anoshin


1 Answers

In the 1st iteration sentence has 0 characters and w has x characters, so you have to copy x characters.

In the 2nd iteration sentence has x characters and w has x characters, so you have to copy 2*x characters.

In the 3rd iteration sentence has 2*x characters and w has x characters, so you have to copy 3*x characters.

In the 4th iteration sentence has 3*x characters and w has x characters, so you have to copy 4*x characters.

And so on...

like image 153
Eran Avatar answered Sep 20 '26 01:09

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!