1

What should be the time complexity of below code snippet

void doSomething(int n) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            doSomeOtherStuff(n);
            doSomething(n - 1);
        }
    }
}

void doSomeOtherStuff(int n) {
    for (int i = 0; i < n; i++) {
        //did some other stuff
    }
}

Is the complexity calculation as: n^2(n + n^2) = O(n^4) is correct? If not please explain

1
  • O(n^4) does seem to be the answer here. Commented Oct 20, 2020 at 17:58

2 Answers 2

2

Per my comments to the first answer, I think the complexity of this algorithm is much worse than O(n^4). @ToddCaywood actually first wrote what I was thinking in my head. This algorithm is actually something like:

O(n^(n^2))

an impossibly bad result. For large datasets, this thing is going to go off into space and never come back.

The way I first looked at this is that each level of recursion adds another set of NESTED for loops. For n==10, you have 20 nested for loops. It just keeps getting deeper and deeper as n grows.

Sign up to request clarification or add additional context in comments.

Comments

0

Yes, O(n^4) is correct.

doSomeOtherStuff(n) is obviously complexity O(n), done n times, also done n times, so the inside portion is O(n^3).

Keeping this in mind, complexity of doSomething(n) [let's call that T(n)] = O(n^3) + T(n-1) where T(n-1) = O(n^3) + T(n-2), etc. Expanding to (n-1)(O(n^3)) + O(n^3) = n(O(n^3)) = O(n^4).

If you need a formal proof, you can follow the logic above pretty easily, expanded where needed.

5 Comments

I don't understand why this is only O(n^4). Don't the number of nested loops go up with n due to the recursion? Isn't it the number of nested loops that determines the 4 in this case? So since there are more than 4 nested loops, isn't this much worse than O(n^4)?
If you look at the inside part of the function and expand outward, it's easier to figure out. So the O(n^3) I think is fairly obvious. For the recursivO(1) + e portion, look at the definition of each step down, and "add" up at the end. So for doSomething(n) = O(n^3) + doSomething(n-1) = O(n^3) + O(n^3) + doSomething(n-2), etc. Going to the end, you have n instances of O(n^3), so multiplying that by another n = O(n^4). There are MUCH more formal proofs for this, for sure.
I see what you're saying. Effectively, the O(n^3) complexity is expanded by n, then n again.... so it's more like O(n^(3*n*n)) = O(n^(n^2))... which is horribly bad. Good call, Steve.
Yes!!! - I was just now trying to form a second chance to help you see that.
Thanks for the chance to make it right ;) Been a while since I was in algorithm classes haha

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.