Factorial with Stack Frames
Compute target factorial by recording pending factors, then unwinding from the base case. The values list is unused.
Compute target factorial by recording pending factors, then unwinding from the base case. The values list is unused.
Input and constraints
- Target must be between 0 and 10.
- Use at most 32 integers. Each numeric input is between -1000 and 1000.
Code inspector
def solve(values, target): stack = [0] * (target) top = 0 n = target while (n > 0): stack[top] = n top = (top + 1) n = (n - 1) result = 1 while (top > 0): top = (top - 1) result = (result * stack[top]) return resultVisualizer
Step 1 of 11Empty structure
Push a pending factorial argument
Push a pending factorial argument.
Variable watch
Step explanation
Push a pending factorial argument.
Worked explanation
Leave one signed order slip at every desk, then collect the answers in reverse desk order.
Guided solution
Replace each factorial call with a pending multiplication. Begin returning at zero factorial, whose value is one.
O(t) time · O(t) auxiliary space
Examples
Worked example · {"values":[],"target":5} ⇒ 120
Edge case 1 · {"values":[],"target":0} ⇒ 1
Edge case 2 · {"values":[],"target":1} ⇒ 1
Progressive hints
Hint 1
Leave one signed order slip at every desk, then collect the answers in reverse desk order.Hint 2
Replace each factorial call with a pending multiplication. Begin returning at zero factorial, whose value is one.Hint 3
Step through the worked example and inspect the highlighted variables before each update.Common mistake
An empty product equals one, including zero factorial.
Interview follow-up
How does a direct recursive function store the same pending work?