You are viewing a single comment's thread. Return to all comments →
am i missing somethign here?
The editorial solution is O(1) how is this faster?
Missed the new O(1) solution was added while the complexity on the right side was still O(N)
While the time spent to compute the number of threes and fives to print is well reduced, you still have to print N digits, so technically the complexity still is O(n).
you see O(1) means that its constant time but the constant(Eg:O(1000000)=O(1)) however big is rewritten as O(1) for the sake of simplicity. well maybe what he is trying to say is that maybe his constant is smaller(i am not sure if it is). i i am just trying to tell you that Alg1 maybe faster than Alg2 even though both of them hve the complexity of O(1).
The loop in this iterative approach will run at most 2 times, which technically makes this solution O(1) as well. However, it should be obvious that the direct formula will require fewer machine instructions. By counting just the math operations (so ignoring jumps, which inflate the cost even more), it breaks down like this (please comment if I made a mistake!):
Direct (2 x N % 3):
+ 1 Multiply
+ 1 Mod
= 2 Constantly
Best Case (N is divisible by 3):
+ 1 Comparison ( while(n > 0) )
+ 2 Comparison and Mod ( if(n%3 == 0) )
Worse Case (N % 3 == 1), full loop runs twice:
+ 3 Comparison ( while(n>0) )
+ 6(3x2) Comparison and Mod ( if(n%3 == 0) )
+ 2(2x1) Subtraction ( n -= 5 )
And we might as well do the 3rd case (loop runs once):
+ 2 Comparison ( while(n>0) )
+ 4(2x2) Comparison and Mod ( if(n%3 == 0) )
+ 1 Subtraction ( n -= 5 )
Since each case is equally likely, we calculate that the average cost is (3+7+11)/3 = 7 instructions.
So although both solutions are O(1), we can correctly conclude that the iterative approach is ~3 times more expensive. If we counted jumps and assignments, it's more like ~4 times. This is a significant difference.