How do you apply recursion and memoization in Dart?
TL;DR: Recursion breaks a problem into smaller subproblems. Memoization caches results of expensive recursive calls to avoid recomputation. Convert recursive to iterative when stack depth is a concern. Dart has no built-in memoize() — use a Map cache.
Full Answer
Recursion is elegant but can be exponential (fib(50) = 2^50 calls without memoization). Memoization is the simplest form of dynamic programming — cache results in a Map<input, output>.
Tail Recursion
Dart does not optimize tail calls. Deep recursion (depth > ~10,000) will StackOverflow. Convert to iterative or use trampolining for very deep recursion.
In Flutter, recursion is common for tree traversal (widget trees, JSON trees). Always consider the maximum depth and add a depth limit guard.
Code Examples
102334155 [1, 2, 4, 5, 3, 6]
Common Mistakes
- ✗Deep recursion without a base case — causes infinite loop / stack overflow
- ✗Using recursion for iterative problems — adds function call overhead; prefer loops for simple iteration
Interview Tip
Fibonacci with memoization is the canonical DP question. Follow up: implement an iterative fibonacci with O(1) space. This shows you understand both top-down (memo) and bottom-up (tabulation) DP.