0

Why is it that inside a for loop and calling a recursive function results to the time complexity of O(2^N) not O(N 2^N) of this code below. Basing on the book CTCI.

void allFib(int n){
    for (int i = 0; i < n; i++) {
        System.out.println(i + ":  "+  fib(i)); 
    }
}

int fib(n){
    if  (n  <=  0)  return 0;
    else if  (n  ==  1)  return 1; 
    return fib(n - 1)  +  fib(n -2);
}
7
  • 3
    Because only the largest part is taken. The same reason iterating through an array twice gives O(n) complexity and not O(2n) complexity. The 2 is dropped. Commented Aug 13, 2019 at 17:43
  • 4
    @MichaelBianconi - then using your logic (exactly as stated) what about O(n Log n)? Commented Aug 13, 2019 at 17:50
  • 1
    @MichaelBianconi that is not correct. In big O notation you drop all constants, but there is a difference in O(2^n) and O(n * 2^n). You may not ignore a nonconstant multiplier. Commented Aug 13, 2019 at 18:01
  • 2
    @MarkRotteveel lol that's not because of large n, that's because 2^0+2^1+...+2^(n-1) is smaller than 2^n. the non-constant factor should never be ignored no matter how large or how small it is Commented Aug 13, 2019 at 18:55
  • 1
    @MarkRotteveel the n term dominates log n in O(n logn). We do not drop the log n term and we shouldn't drop it here either Commented Aug 13, 2019 at 18:58

1 Answer 1

2

Think of your recursive function as computing values in a tree.

        fib(n)
         /\
        /  \
 fib(n-1)   fib(n-2)

If you look carefully for n = 2, there are 3 values to be computed which is 2^(1+1) - 1 = 3 where 1 here is the height of the tree as in2^(h+1)-1

for n = 3, the height is h = 2

for n = 4, the height is h = 3

For all n, you need to add all of those: 2^2 - 1 + 2^3 - 1 + 2^4 - 1 + ....2^n - 1 -> is of the order of 2^(n+1)

Hence you get O(2^n)

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.