GeeksforGeeks » Algorithms

TIME COMPLEXITY PROBLEM

(4 posts)
  • Started 3 months ago by pasinhal
  • Latest reply from atul007

Tags:

  1. pasinhal
    Member
    Posted 3 months ago #

    What will be the time complexity T(n) and space complexity S(n) of the following Algorithm?
    How can we build a recursion tree for the same?

    Large(n)
    {
            If(n<=1)
                  Return n;'
             Sum = 0;
             For i= 1 To n-1
                   Sum = Sum + Large(i);
             Return Sum;
    }
  2. kartik
    Moderator
    Posted 3 months ago #

    T(n) = Sum of T(i) for i = 1 to n - 1 + C

    Where C is constant for operations other than recursive calls.

    The recursion tree will look like following:

    Step 1:
                                    C
                       /           |       ...\
                T(n-1)    T(n-2)     T(1)
    
    
    
    Step 2:
                                                                       C
                                                  /                    |             \
                                               /                       |               \
                                             C                        C        ...     C
                                        /   | ..  \                  /..\
                             T(n-2)  T(n-1)..T(1)
    

    Recursion tree method doesn't seem very helpful here to find the complexity. You can find the complexity by considering base cases one by one

    T(1) = C
    T(2) = T(1) + C = 2C
    T(3) = T(2) + T(1) + C = 4C
    T(4) = T(3) + T(2) + T(1) + C = 8C
    T(5) = T(4) + T(3) + T(2) + T(1) + C = 16C

    You can see that the complexity increases in powers of 2. So T(n) would be O(2^n)

  3. pasinhal
    Member
    Posted 3 months ago #

    Thanks. But what will be the space complexity?

  4. atul007
    Member
    Posted 3 months ago #

    space complexity is O(n).


Reply

You must log in to post.

RSS feed for this topic