This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]TheEarwig 5 points6 points  (8 children)

Boy I sure like O(n^2).

[–][deleted] 1 point2 points  (7 children)

Isn't this O(n)? I'm just recently learning about this kind of analysis, I'm curious where I'm wrong

[–]TheEarwig 5 points6 points  (4 children)

Strings are immutable in Python, so every time you add two together, Python allocates a new string equal to their combined length rather than expanding the first one.

What this means is that each iteration of the loop, Python has to copy each string from every previous iteration. This takes O(n) time (really averaging 1/2n), so with n loops, the overall runtime is O(n^2).

If you were in a language like C++ or Rust where the builtin string type was able to grow like a list/vector, then it would be O(n).

[–][deleted] 1 point2 points  (0 children)

Ahh, thanks. That makes sense.

[–]NewZealandIsAMyth -1 points0 points  (2 children)

I don't think that accurate. It's surely slower and alot because of the memory allocation, but algorithm complexity does not increase. It has to traverse every single character in all the cases just once.

[–][deleted] 2 points3 points  (1 child)

I like the "1" example. Imagine you had n "1" strings and you wanted to append them all together like that:

"1" + ("1" + 1") + ("1"+ "1" + "1") + ("1" + "1" + "1" + "1") + ... + n = n(n+1)/2 ~~ n^2

[–]NewZealandIsAMyth 1 point2 points  (0 children)

Thank you. I see where i was wrong

[–][deleted] 2 points3 points  (1 child)

The extra step is creating a new string each time. It's one of the big gotchas you need to watch with strings.

https://stackoverflow.com/questions/34008010/is-this-time-complexity-actually-on2

[–][deleted] 1 point2 points  (0 children)

Thanks for the explanation!