I am wondering how to calculate time complexity of such combination:
"some string"
.split(" ") // O(n)
.map(
word => doSomething(word) // word length = j, doSomething(word) => O(j)
) // O(n * j) => O(n^2) ???
doSomething
is a linear complexity function, doesn't metter what its doing.
So, according to Big O of javascript built-in split function , time complexity of .split(" ")
will be O(n)
On next line we have a .map
on words array, which in worst case can be O(n/2)
=> O(n)
when we have all words containing one char.
Inside map function we do some operation on the word with length j
=> O(j)
. Taking into account, that word can be size of full string (no spaces) O(j) => O(n)
As result we have overal time complexity O(n^2)
BUT if we have worst case on .map step O(n)
then we can't have worst case inside map, becase overall sum of all words length is size of input string. So we can't convert O(j) to O(n)
What will be time complexity then ?
Update
Ok, i made some experimental measures and here what i've got on my pc https://www.wolframalpha.com/input/?i=listplot%5B%7B%7B10%2C+0.015%7D%2C%7B100%2C+0.1%7D%2C%7B1000%2C+0.72%7D%2C%7B10000%2C+8.5%7D%2C%7B100000%2C+67.89%7D%2C+%7B1000000%2C+642.60%7D%2C+%7B10000000%2C+6657.4%7D%2C+%7B100000000%2C+70076.01%7D+%7D%5D
X axis => time ms
Y axis => input string length
data generated randomly
The complexity is clearly linear.