I was asked at an interview, the efficient way to solve a problem checking for pallindrome.
Now i can do two things:
The second is recursive. My question is what is the difference in the space complexity of an algorithm's recursive and non-recursive versions?
Therefore, The time complexity of recursive factorial is O(n). As there is no extra space taken during the recursive calls,the space complexity is O(N).
Stack space in recursive calls counts too as extra space required by a program.
The space complexity for DFS is O(h) where h is the maximum height of the tree.
So, the space occupied by the array is 4 * n. Also we have integer variables such as n, i and sum. Assuming 4 bytes for each variable, the total space occupied by the program is 4n + 12 bytes. Since the highest order of n in the equation 4n + 12 is n, so the space complexity is O(n) or linear.
Have a read at
Basically, a recursive algorithm will add overhead since you store recursive calls in the execution stack.
But if the recursive function is the last line of the call (tail recursion) then there is no additional penalty.
That is of course both algorithms are the same.
In theory they have the same space complexity; it largely depends on whether tail recursion can be optimized.
If so, the stack gets replaced at every recursion so it doesn't incur a penalty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With