Redirected
retagged by
1,452 views
0 0 votes

Consider the following 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);
    return fun(arr,n-1,X) || fun(arr,n-1,X - arr[n-1]*arr[n-1]);
}

Which of the following is true about the 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

2 Answers

6 6 votes
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).
Position:
Show:

Related questions

1 1 vote
1 1 answer
2.9k
2.9k views
Aditya Bahuguna asked Jan 7, 2018
2,911 views
The binary search algorithm is implemented using recursion. Then the space complexity is$\mathrm{O}(1)$$\mathrm{O}(\mathrm{n})$$\mathrm{O}(\log \mathrm{n})$$O(n \log n)$
0 0 votes
0 0 answers
417
417 views
Misbah Ghaya asked Aug 17, 2022
417 views
Please list out the best free available video playlist for Asymptotic Worst-Case Time and Space Complexity from Algorithm as an answer here (only one playlist per answer)...
0 0 votes
2 answers 2 answers
1.5k
1.5k views
Rustam Ali asked Sep 3, 2018
1,455 views
Find time complexity of below Program?A(n){if(n<=1) return;elsereturn $A(\sqrt{n})$ ;}
9 9 votes
2 answers 2 answers
6.9k
6.9k views
vineet.ildm asked Nov 7, 2016
6,876 views
Why space complexity of heapsort is O(1)....and why not O(logn)..because of space required by recursion calls which is equivalent to height of the tree...where am i getti...