patternModerate
Time complexity of a triple-nested loop
Viewed 0 times
triplelooptimenestedcomplexity
Problem
Please consider the following triple-nested loop:
The statement here is executed exactly $n(n+1)(n+2)\over6$ times. Could someone please explain how this formula was obtained? Thank you.
for (int i = 1; i <= n; ++i)
for (int j = i; j <= n; ++j)
for (int k = j; k <= n; ++k)
// statementThe statement here is executed exactly $n(n+1)(n+2)\over6$ times. Could someone please explain how this formula was obtained? Thank you.
Solution
You can count the number of times the innermost for loop is executed by counting
the number of triplets $(i,j,k)$ for which it is executed.
By the loop conditions we know that: $1 \leq i \leq j \leq k \leq n$ . We can reduce it to the following simple combinatorics problem.
So, we just need to count the number of ways of picking 3 boxes from $n+2$ boxes which is $n+2 \choose 3$.
the number of triplets $(i,j,k)$ for which it is executed.
By the loop conditions we know that: $1 \leq i \leq j \leq k \leq n$ . We can reduce it to the following simple combinatorics problem.
- Imagine $n+2$ boxes of red colour placed in an array from left to right.
- Pick any 3 boxes from the $n+2$ boxes and paint them blue.
- Form a triplet $(i,j,k)$ as follows:
- $i$ = 1 + number of red coloured boxes to the left of first blue box.
- $j$ = 1 + number of red coloured boxes to the left of second blue box.
- $k$ = 1 + number of red coloured boxes to the left of third blue box.
So, we just need to count the number of ways of picking 3 boxes from $n+2$ boxes which is $n+2 \choose 3$.
Context
StackExchange Computer Science Q#3306, answer score: 14
Revisions (0)
No revisions yet.