Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity or Big O notation for "str.replace()" built In function in Javascript?

I am confused if the time complexity for str.replace() function is O(n) or O(1), for example:

var str = "Hello World";
str = str.replace("Hello", "Hi");
console.log(str);
//===> str = "Hi World"  

Is it always the same answer or does it depend on what we replace?
Any thoughts or helpful links?!

like image 867
Zainab Hammami Avatar asked Nov 09 '17 18:11

Zainab Hammami


People also ask

What is the time complexity of string replace?

They'll do a simple string replacement like this in a single pass using O(n) time and O(1) space.

What is time complexity and Big O notation?

The Big O Notation for time complexity gives a rough idea of how long it will take an algorithm to execute based on two things: the size of the input it has and the amount of steps it takes to complete. We compare the two to get our runtime.

What is the big O complexity of the function?

Big O notation is used to describe the complexity of an algorithm when measuring its efficiency, which in this case means how well the algorithm scales with the size of the dataset.

What is Big O notation in Javascript?

Big O Notation is used in computer science to analyse the performance of an algorithm (an algorithm is just another name for a function – a set of instructions). Big O specifically looks at the worst-case scenario of an algorithm – looking at the big picture.


2 Answers

Firstly it should be

str = str.replace("Hello", "Hi");

Secondly,

searching a substring inside a string can be done in linear time using KMP algorithm which is the most efficient. Replacing in the worst case will take linear time as well.

So overall time complexity: O(n)

Here n is dependent on the string str. In the worst case it will end up traversing the whole string and still not find the searchValue given to the replace function.

like image 173
Rahul Arora Avatar answered Oct 01 '22 07:10

Rahul Arora


It's definitely not O(1) (comparison of string searching algorithms) , but ECMAScript 6 doesn't dictate the search algorithm:

Search string for the first occurrence of searchString and let pos be the index within string of the first code unit of the matched substring and let matched be searchString. If no occurrences of searchString were found, return string.

So it depends on the implementation.

Is it always the same answer or does it depend on what we replace?

Generally, it will be slower for longer search strings. How much slower is implementation-dependent.

like image 25
David Ehrmann Avatar answered Oct 01 '22 07:10

David Ehrmann