What is the big Oh notation for str.replace
function in Python ?
Is it always O(n) ?
str = "this is string example"
print str.replace("is", "was")
thwas was string example
Python String replace() Method The replace() method replaces a specified phrase with another specified phrase. Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.
Big Oh Notation, Ο The notation Ο(n) is the formal way to express the upper bound of an algorithm's running time. It measures the worst case time complexity or the longest amount of time an algorithm can possibly take to complete. Ο(f(n)) = { g(n) : there exists c > 0 and n0 such that f(n) ≤ c.
The replace() method is a built-in functionality offered in Python programming. It replaces all the occurrences of the old substring with the new substring. Replace() returns a new string in which old substring is replaced with the new substring.
The Python replace() method is used to find and replace characters in a string. It requires a substring to be passed as an argument; the function finds and replaces it. The replace() method is commonly used in data cleaning.
Big O notation is calculated at worst-case scenario, and Python sources for worst case do just 'find next position of substr, replace, and go further'. One replacement does O(n) operations (copying the string). One search, according to http://effbot.org/zone/stringlib.htm, in worst-case scenario does O(n*m) operations. And since it can be up to n/m replacements, in total it should be surprisingly O(n*n).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With