I\'m studying for a test and found this question:
I can\'t really determine the complexity, I figured it\'s either O(n2) or O(n3) and I\'m lea
The complete reasoning is as follows:
Let n
be the length of the array.
1) There are three nested loops.
2) The innermost loop performs exactly j-i
iterations (k
running from i+1
to j
inclusive). There is no premature exit from this loop.
3) The middle loop performs exactly n-j
iterations (j
running from i
to n-1
inclusive), each involving j-i
innermost iterations, in total (i-i)+(i+1-i)+(i+2-i)+... (n-1-i) = 0+1+2... + (n-1-i)
. There is no premature exit from this loop.
4) The outermost loop performs exactly n
iterations (i
running from 0
to n-1
inclusive), each involving 0+1+2+ ... (n-1-i)
innermost iterations. In total, (0+1+2... n-1) + (0+1+2+... n-2) + (0+1+2+... n-3) + ... (0)
. There is no premature exit from this loop.
Now how do handle handle this mess ? You need to know a little about the Faulhaber's formula (http://en.wikipedia.org/wiki/Faulhaber%27s_formula). In a nutshell, it says that the sum of integers up to n
is O(n^2)
; and the sum of the sum of integers up to n
is O(n^3)
, and so on.
If you recall from calculus, the primitive of X
is X^2/2
; and the primitive of X^2
is X^3/3
. Every time the degree increases. This is not by coincidence.
Your code runs in O(n^3)
.