I am trying to find the time complexity of str.replace()
built into python, and this is the data I've managed to gather (here and on other sites):
I know replace()
is based on the Boyer–Moore algorithm, which takes worst-case time of O(n*m) to find a substring, but is this for a single substring?
Does replace()
return a copy of the "fixed" string when it finds the first substring and then start to search again?
And what about when we have multiple occurrences of a substring, like the following example:
old_string = '192.168.1.1'
new_string = old_string.replace('.', '|')
If it can only replace one substring at a time, then for a single substring we get O(n*m), times the number of substrings which is a maximum of n/m. This comes to O(n^2)!
Given that a simple loop would take O(n), like:
old_string = '192.168.1.1'
new_string = []
for ch in old_string:
new_string.append('|' if ch == '.' else ch)
Does that make sense? Am I missing something?
Could the built in replace() be flawed for multiple replacements, or is it implemented in a way to continue where it left off?