A long string s
contains only 0
and 1
. This Ruby code counts how many 1
there are:
s.gsub(/1/).count
What is the time complexity in Big O notation? Is there a tool to do the calculation?
A long string s
contains only 0
and 1
. This Ruby code counts how many 1
there are:
s.gsub(/1/).count
What is the time complexity in Big O notation? Is there a tool to do the calculation?
As far as I know there is not a generic tool to calculate Big O notation for arbitrary code - this would be a hard task - for a start it is not always clear which scaling issue to measure. Even very simple logic,
a = b + c
does not scale as you might think - if you need to allow for arbitrarily large numbers then this is notO( 1 )
.The simplest thing to do is benchmark and plot the results. You should be aware that for highly efficient code that the scaling measure can be "drowned out" by for example method-calling overhead. So it takes a little effort - you need to find values of N large enough that doubling it makes a significant difference.
To verify that your command is
O( N )
on string length, I ran the following benchmarks:By inspection you can see this is a simple linear relationship - every time I double the length of the string, the time taken (roughly) doubles.
By the way,
s.count('1')
is much, much faster, but is alsoO( N )
:You could take the return values from benchmarking, and use them to automate a guess at Big O. This is probably what services like codility do.