What is the complexity of this simple piece of code?

前端 未结 10 1265
遇见更好的自我
遇见更好的自我 2020-11-29 04:28

I\'m pasting this text from an ebook I have. It says the complexity if O(n2) and also gives an explanation for it, but I fail to see how.

Question: What i

10条回答
  •  庸人自扰
    2020-11-29 05:21

    As the explanation given in the book, for ever word in the string array a new object of sentence gets created and that sentence object first copies the previous sentence and then traverses till the end of the array and then appends the new word, hence the complexity of n^2.

    1. First 'n' to copy the previous sentence into a new object
    2. Second 'n' to traverse that array and then append it

    Hence n*n will be n^2.

提交回复
热议问题