Ad
  • Custom User Avatar

    This comment is hidden because it contains spoiler information about the solution

  • Default User Avatar

    To be honest I don't know either that's why I suggested "trying" withoput pointing out a potential "mistake/useless operation" (I have tried the same thing and it times out compared to the += approach and the two solutions have 8 secs difference between them). I have tried to time both approaches on my local machine and it seems to be minor. Theoretically, I don't think there is a difference because strings are immutable and both approaches should create a new string (as far as I understand). I am looking through the cpython github and if I find something I will update the thread.

    Update: I have tried OP's solution as is and it timed out. I have tried the inplace addition and reversing and it worked. I have also tried appending (without inplacing) but at the end and not the beginning then reversing and it also worked. So that seems to be what makes a difference. I am not sure how strings are implemented in python (probably linked lists or something similar) but once I can find the source code for (which I couldn't find, can't find a "_string" file on the github repo) I will update my reply.

    Update 2: Check this stack overflow thread : https://stackoverflow.com/questions/37133547/time-complexity-of-string-concatenation-in-python. In the accepted answer's footnote there is a mention of an optimisation to string concatenation. In short when you define two string strA and strB, cpython will avoid creating a new copy when using strA = strA + strB or strA+=strB but not when using strA = strB + strA (prepending). This is in line with what I found so I think it is correct. I hope This helps. Take it with a grain of salt though.

    If anyone has a better answer or explanation, then please correct me and/or append to the thread.

  • Custom User Avatar

    This comment is hidden because it contains spoiler information about the solution

  • Default User Avatar

    This comment is hidden because it contains spoiler information about the solution

  • Custom User Avatar

    I will not be able to say more precisely.If you will realise it right, you would find solution not so hard. But without seeing your option I can't be more specific. May be only "try to use step debuging" )