Is the space complexity of a recursive algorithm necessarily at least as large as the depth of the recursive call?


Is the space complexity of a recursive algorithm necessarily at least as large as the depth of the recursive call?
I am having trouble determining when recursive functions are sub-optimal to their iterative counterparts when space is an issue. When writing recursive functions, is the space complexity necessarily at least as large as the depth of the recursive call if it is not tail recursive?
For example, lets remove duplicates from a linked list using recursion. This can be done trivially with an iterative approach in O(n^2) time and O(1) space. But is the recursive variant also O(1) space?
removeDuplicatesRecursive() {
let current = this.head;
while (current.next) {
if (this.head.data === current.next.data) {
current.next = current.next.next
} else {
current = current.next;
}
}
if (this.head.next) {
removeDuplicatesRecursive(this.head.next);
}
return head;
}
removeDuplicatesRecursive()
In addition, consider why Stack Overflow errors exist. If recursion was O(1) space, why is there a limit to how many times you can recurse?
– Patrick Roberts
7 mins ago
1 Answer
1
In the above program, the space complexity is O(n)
.
O(n)
For recursion, until you reach the base condition, every call to the recursive function including all the arguments, local variables are put into call stack.
For the above program, the most number of function calls happens, when all the elements of the linked list are unique. In that case, n
function calls will be made and space complexity will be O(c * n) ~ O(n)
.
n
O(c * n) ~ O(n)
the worst case of space complexity happens, when all the elements of the linked list are unique.
If the above method was implemented properly, it would always reach the worst case of space complexity, because it always recurses the entire linked list. This is not conditional on whether the elements are unique.– Patrick Roberts
5 mins ago
the worst case of space complexity happens, when all the elements of the linked list are unique.
When there will be some duplicates, those elements will be deleted so there will be no call for those elements. In big-O perspectives, yes it will be always
O(n)
.– Kaidul Islam
3 mins ago
O(n)
@PatrickRoberts I've edited my answer :)
– Kaidul Islam
1 min ago
That makes more sense; for some reason I wasn't considering the removed elements as limiting the number of calls.
– Patrick Roberts
32 secs ago
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Your recursive algorithm does not make sense.
removeDuplicatesRecursive()
is written as a member method yet you call it statically and pass an argument that is unused.– Patrick Roberts
8 mins ago