Workspace Factorial
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Factorial with Stack Frames visualizer

Compute target factorial by recording pending factors, then unwinding from the base case. The values list is unused.

EXECUTION LAB

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 result

Visualizer

Step 1 of 11

Empty structure

Push a pending factorial argument

Push a pending factorial argument.

Variable watch

n 5top 0stack [0,0,0,0,0]

Step explanation

Push a pending factorial argument.

comparisons 1reads 0writes 0swaps 0recursiveCalls 0
Educational simulation · O(t) time · O(t) space

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 1Leave one signed order slip at every desk, then collect the answers in reverse desk order.
Hint 2Replace each factorial call with a pending multiplication. Begin returning at zero factorial, whose value is one.
Hint 3Step 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?

Continue learning

Practice related DSA questions in the same topic.