GATE CSE
First time here? Checkout the FAQ!
x
0 votes
83 views
QUESTION 14 : Consider the below Pseudo code written in C style 
bool fun(int arr[], int n, int X) {  
    if (X == 0)     
        return true;  
    if (n == 0 && X != 0)    
        return false;   
    if (arr[n–1]*arr[n–1] > X)     
        return fun(arr, n–1, X);  
  // Here "|| "indicates logical or  
  return fun(arr, n–1, X) || fun(arr, n–1, X – arrr[n–1]*arr[n–1]); 
}

Which of the following is true about above code. 
A) Time Complexity of fun() is O(2n) and it requires O(n) extra space 
B) Time Complexity of fun() is O(2n) and it requires O(n2) extra space 
C) Time Complexity of fun() is O(n2) and it requires O(n) extra space 
D) Time Complexity of fun() is O(n2) and it requires O(n2) extra space 
Correct – A

How to calculate space complexity?

asked in Algorithms by Active (1.5k points)   | 83 views

1 Answer

+5 votes
Best answer
See how many function calls are active in the stack. Here, function 'fun(n)' can give a call to fun(n-1), which inturn will call fun(n-2) and so on.. till n=0.

When n becomes 0, fun will start returning, ie, it starts popping out of the stack. So, at max, there are n to 0, functions in the stack. Hence space complexity is O(n).
answered by Loyal (3.3k points)  
selected by
Top Users Jan 2017
  1. Debashish Deka

    8126 Points

  2. sudsho

    5042 Points

  3. Habibkhan

    4706 Points

  4. Vijay Thakur

    4458 Points

  5. Bikram

    4348 Points

  6. saurabh rai

    4212 Points

  7. Arjun

    4010 Points

  8. santhoshdevulapally

    3722 Points

  9. GateSet

    3292 Points

  10. Sushant Gokhale

    3286 Points

Monthly Topper: Rs. 500 gift card

19,122 questions
24,033 answers
52,725 comments
20,276 users