GATE CSE
First time here? Checkout the FAQ!
x
0 votes
135 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)   | 135 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.6k points)  
selected by


Top Users Apr 2017
  1. akash.dinkar12

    3514 Points

  2. Divya Bharti

    2546 Points

  3. Deepthi_ts

    2040 Points

  4. rude

    1966 Points

  5. Tesla!

    1768 Points

  6. Shubham Sharma 2

    1610 Points

  7. Debashish Deka

    1588 Points

  8. Arunav Khare

    1454 Points

  9. Kapil

    1424 Points

  10. Arjun

    1420 Points

Monthly Topper: Rs. 500 gift card

22,076 questions
28,042 answers
63,234 comments
24,135 users