Understanding Recursive Algorithm Run Time & Space Complexity
Time Complexity
In recursive algorithms determing the time complexity is defined as follows:
Time Complexity = (Depth of Recursion/Call Stack) × (Work Done per Call)
Time Complexity Examples
If the depth of stack is in the worst case O(n) and in each execution we also do O(n) work then it would O(n2)
O(n)∗O(n)=O(n2)
If the depth of stack is O(logn) but we do O(n) work in each execution then the time complexity is O(nlogn)
O(logn)∗O(n)=O(nlogn)
Space Complexity
In recursive algorithms determing the space complexity is defined as follows:
Space Complexity = (Depth of Recursion) × (Space Required per Call)
Space Complexity Examples
If we have an algorithm with a depth of call stack of O(logn) but in each stack we have O(1) space, it would be O(logn)
O(logn)∗O(1)=O(logn)
Whereas if depth is O(logn) but in each call we allocate O(n) space it would be O(nlogn) space
O(logn)∗O(n)=O(nlogn)