Compute five factorial with a loop.
Acceptance criteria
- 1.#out should show result 120.
DSA Tutorial · Recursion
These 10 tasks go with the Turning Recursion Into Iteration chapter. 5 of them ask you to build something small from scratch; 5 give you code that is already broken and ask you to work out why. Set aside about 90 minutes for the whole set, though you can do them in any order.
Nothing here is marked by a person. When you press Submit, the editor checks your code against the points listed under each task and tells you straight away what passed and what didn't (you need a free account to submit). If you get stuck, there are hints, and a worked solution once you've had a go. The first 2 tasks are free; the rest are part of the practice plan.
If it's been a while since you read the chapter, here is how it starts: “Recursion uses the call stack. An iterative version uses a stack you control. The logic is identical; the difference is that your stack lives on the heap and does not overflow at ten thousand frames.” .
1.Loop instead of recursingexercise · easy · 10 min
Compute five factorial with a loop.
Passes when: #out should show result 120.
2.Rolling Fibonacciexercise · easy · 10 min · practice plan
Compute the tenth Fibonacci number with two variables.
Passes when: #out should show fib 55.
3.Walk with an explicit stackexercise · easy · 10 min · practice plan
Traverse a tree using a stack and join the values.
Passes when: #out should show 1-2-3.
4.Sum with a loopexercise · easy · 10 min · practice plan
Add every value iteratively.
Passes when: #out should show sum 6.
5.Avoid the stack limitexercise · medium · 10 min · practice plan
Count to 100000 in a loop and report that it finished.
Passes when: #out should show finished.
6.Fix the loop starting at zerobug fix · easy · 8 min
Multiplying by zero makes the whole product zero.
Passes when: #out should show result 120.
7.Fix the rolling update losing a valuebug fix · easy · 8 min · practice plan
Assigning one variable before the other overwrites what is still needed.
Passes when: #out should show fib 55.
8.Fix the children pushed in orderbug fix · medium · 8 min · practice plan
Pushing left first means the stack pops it last.
Passes when: #out should show 1-2-3.
9.Fix the accumulator inside the loopbug fix · easy · 8 min · practice plan
Resetting the total each pass keeps only the last value.
Passes when: #out should show sum 6.
10.Fix the deep recursionbug fix · easy · 8 min · practice plan
A hundred thousand frames overflows the stack, so a loop is needed.
Passes when: #out should show finished.
Between them these tasks cover Explicit stacks, Tail calls and Rolling variables.
Looking for a different chapter? See every practice set, or switch to the interview theory questions.