-1

why running time of this code is O(n^2).(as written in cracking the coding interview book).and how it could be improved

public String makeSentence(String[] words) {
    StringBuffer sentence = new StringBuffer();
    for (String w : words) sentence.append(w);
    return sentence.toString();
}
ugan jha
  • 43
  • 1
  • 9

2 Answers2

1

For n = the number of elements in the words array

The for loop means at least O(n)

Inside the for loop, each instance of sentence.append(w) should be "constant" since sentence is a StringBuffer.

Doing constant things n times means you get a total of O(n)

Kache
  • 15,647
  • 12
  • 51
  • 79
0

The key line to look at is for (String w : words) sentence.append(w);

In Java, a String append is an O(n) operation. Because the append is inside the for loop, the method as a whole is O(n^2).

therealrootuser
  • 10,215
  • 7
  • 31
  • 46