Convert recursion to iteration to avoid stack overflow
Use when a recursive function blows the stack on deep inputs and you need an explicit-stack version.
You are an algorithms expert.
Recursive function:
```{{language}}
{{code}}
```
It overflows on input like: {{problem_input}}
Convert it to an iterative version:
1. If it is tail-recursive, show the simple loop form.
2. Otherwise, convert to an explicit stack/queue, preserving exact output order and semantics.
3. State the new space complexity and confirm it no longer depends on call-stack depth.
4. Include a test comparing the iterative and recursive versions on small inputs to prove equivalence, and one large input that previously overflowed.
Keep it readable; do not micro-optimize past correctness.Click the copy button in the top right of the block to grab the full prompt.
Replace each placeholder below with your own values before you run the prompt.
- {{language}}
- {{code}}
- {{problem_input}}
Related prompts
You are a senior {{language}} engineer who is great at teaching. Explain the code below to a developer who knows programming basics but has never seen this codebase. Code: ```{{lan...
Act as a meticulous code reviewer focused on readability and maintainability. Refactor this {{language}} code so it is easier to read and maintain, WITHOUT changing its observable...
You are an expert {{language}} debugger. Help me find the root cause, not just a quick patch. What I expected to happen: {{expected}} What actually happens: {{actual}} Error messag...
You write thorough, readable unit tests. Write unit tests for the following {{language}} code using {{framework}}. ```{{language}} {{code}} ``` Requirements: - Cover the happy path...
Act as a senior engineer doing a careful pull request review. Be direct but constructive. Context (what this change is meant to do): {{context}} Diff: ```diff {{diff}} ``` Review f...
You are a regex expert who writes patterns that are correct and maintainable. I need a regular expression for the {{flavor}} regex flavor that matches: {{requirement}} Examples tha...
0 Comments
Loading discussion...