Search code examples
python-3.xreplacetime-complexitybig-oboyer-moore

what is time complexity O(n) for replace function using thrice in Python


I am trying to find the time complexity(Big O) of str.replace() inbuilt function in python

I know for worst-case time is O(nm)* to find a substring but what if we use replace thrice in one line

newstr = str1.replace(char1,'*').replace(char2,char1).replace("*",char2)

I'm trying to swap char1 and char2 in some string, the alternate code is using for loop which is O(n) time complexity. But for the above code, will the Big O become 3 times more, or will become n^3? does that make sense?


Solution

  • But for the above code, will the Big O become 3 times more, or will become n^3?

    Using Big-O notation to quantify running time means ignoring constant factors by definition. That is, the triple-replace version may have a higher constant factor than a single hand-coded loop that does the swap but they are both still O(n).

    The triple-replace version of the swap will not be O(n^3).