ProgrammingHardAmazon OA · Flipkart coding round

Which technique is the reliable fix for a recursive DFS on a path graph with n = 10^5 nodes in Python, which otherwise raises RecursionError?

  1. A. Use yield from so the recursion uses no call stack
  2. B. Rewrite the DFS with an explicit stack or deque, since the default recursion limit is about 1000 frames
  3. C. Wrap the call in try/except RecursionError and retry with the same recursion
  4. D. Add @lru_cache to the DFS function so it stops recursing

Correct answer: B. Rewrite the DFS with an explicit stack or deque, since the default recursion limit is about 1000 frames

An explicit stack keeps the traversal state in heap memory, so the depth does not hit the interpreter's frame limit. Caching or wrapping does not reduce the number of nested calls.

More Python Programming questions

Exams that ask this topic