Is the space consumed by linear search (recursive) and linear search…
2024
Is the space consumed by linear search (recursive) and linear search (iterative) the same?
- A.
No, recursive algorithm consumes more space
- B.
No, recursive algorithm consumes less space
- C.
Yes
- D.
Nothing can be said
Attempted by 51 students.
Show answer & explanation
Correct answer: A
Space complexity of an algorithm counts the auxiliary memory it needs beyond the input, and function calls are not free: each call frame requires stack memory for its own copies of parameters, local variables, and the return address, held until that call returns. A loop, by contrast, reuses a single fixed set of variables across all iterations, adding no per-iteration stack overhead.
Iterative version: keeps one index variable and updates it inside the loop — at any point exactly one stack frame (the function's own) exists, so auxiliary space is O(1).
Recursive version: calls itself with an incremented index at each step — the call checking index 0 calls the one checking index 1, which calls the one checking index 2, and so on; none of these returns until the base case (element found or end of array) is hit.
At the deepest point there can be up to n live stack frames simultaneously, each holding its own copy of the index/array-bound parameters, so auxiliary space for the recursive version is O(n).
This matches the general rule that any recursive-to-iterative rewrite trades call-stack depth for loop-variable reuse: a recursive call still occupies its own stack frame unless the language/compiler performs tail-call elimination (not assumed here), so O(n) stack usage for recursion versus O(1) for iteration is the standard space-complexity comparison for linear search.