Recently I gave Codeforces round #660 (Div 2) ============================================= ,
where i solved problem B in O(n) time complexity After doing the problem in O(n) I still get TLE !!! and its not only me I get to know many other also faced this problem
EVEN C++ O(n) SUBMISSION GOT TLE !!!!!
My submission : http://codeforces.net/contest/1388/submission/88472454
A C++ Submission : https://codeforces.net/contest/1388/submission/88470034
Auto comment: topic has been updated by jay__0208 (previous revision, new revision, compare).
For 1, I think it's PyPy.
I tested the code in custom test. With Python 3.7.2 I got 124ms, but with PyPy 3.6 I got 2261ms.
For 2, It's $$$\mathcal{O}(n^2)$$$.
string::operator=
is $$$\mathcal{O}(n)$$$ and you used it $$$\mathcal{O}(n)$$$ times. The correct way is usingstring::operator+=
.The runtime of Python string concatenation is the length of the combined string, not O(1)
https://stackoverflow.com/questions/37133547/time-complexity-of-string-concatenation-in-python
You code therefore runs in O(n2).
You will get familiar with Python data structures over time. Today I learnt how to call a function recursively in Codeforces.
No actually loujunjie is correct , and the same code is running properly in python 3 where as not in pypy 3 but codeforces only says pypy is always faster than python
Ok, he is correct. I am still new ...
It says almost always, and that is true in my experience.
In python, strings are immutable.
When you concatenate strings then it creates a new instance.
So every time you add a character to a string it creates a new instance of that string which takes O(n) time. And you do this n times so O(n*n).It's always better to use list instead of string in such cases.It's not true. Python interpreter developers already added the optimization for this pattern back in 2004.
+=
is slow (compare tojoin
), but not so slow to be $$$\mathcal{O}(n)$$$ each time. But It seems PyPy doesn't have this optimization, leading to the TLE of OP.This makes sense. you are right they added optimization but it is very slow as compared to join. I tried same code with
n = 10^7
. And it took7.8 sec
with+=
and1.5 sec
withjoin
. So asymptotically+=
is not O(1) (not even amortized).IMO,
join
is best practice.https://codeforces.net/contest/1388/submission/88530339
https://codeforces.net/contest/1388/submission/88530040
Might help
Please don't shout.