factorial(0) = 1, otherwise factorial(n) = n * factorial(n - 1). The smallest example of recursion with a single base case, used to visualise the call stack growing on descent and shrinking on unwind.

Algorithm

Canonical input n = 5 gives factorial(5) = 120. The replay shows six descent frames and five unwind frames (11 total).

Basic Implementation

basic.dart
int factorial(int n) {
  if (n == 0) {
    return 1;
  }
  return n * factorial(n - 1);
}

void main() {
  final result = factorial(5);
  print(result);
}

Complexity

  • Time: O(n)
  • Space: O(n) call stack

Implementation notes

  • Dart: no need to grow the stack size at this depth; the standalone Dart VM handles n = 5 trivially.
  • The replay shows the call-stack contents on each frame and the computed n * factorial(n-1) value on each unwind, matching the lesson spec.
descend then unwind Each non-base call awaits the result of the next call, then multiplies.