Stack Overflow Prevention - Problem

Write a recursive function that calculates the factorial of a number with a built-in depth limit to prevent stack overflow. The function should throw a custom error when the recursion depth exceeds the specified limit.

Requirements:

  • Implement a recursive factorial function with a depth counter
  • Throw a custom error message when depth limit is exceeded
  • Return the factorial result if computation succeeds within the limit

Custom Error Format: "Error: Recursion depth limit exceeded"

Input & Output

Example 1 — Successful Calculation
$ Input: n = 5, maxDepth = 10
Output: 120
💡 Note: Factorial of 5 is 5! = 5 × 4 × 3 × 2 × 1 = 120. Recursion depth is 5, which is less than maxDepth of 10, so calculation succeeds.
Example 2 — Depth Limit Exceeded
$ Input: n = 8, maxDepth = 5
Output: Error: Recursion depth limit exceeded
💡 Note: Calculating 8! would require 8 recursive calls, but maxDepth is only 5, so the function throws an error before stack overflow occurs.
Example 3 — Edge Case at Limit
$ Input: n = 3, maxDepth = 3
Output: 6
💡 Note: Factorial of 3 requires exactly 3 recursive calls, which matches maxDepth of 3. This is the boundary case where calculation just succeeds.

Constraints

  • 1 ≤ n ≤ 20
  • 1 ≤ maxDepth ≤ 100
  • Function must track recursion depth accurately
  • Error message must match exactly: "Error: Recursion depth limit exceeded"

Visualization

Tap to expand
INPUTALGORITHM STEPSRESULTn = 5factorialmaxDepth = 3safety limitCalculate 5! but stop if recursiongoes deeper than 3 levels1Start factorial(5, depth=1)2Check: depth=2 ≤ 3 ✓3Check: depth=3 ≤ 3 ✓4Check: depth=4 > 3 ✗STOP! Throw ErrorERROR THROWNRecursion depth limitexceededStack overflow prevented!Key Insight:Depth tracking prevents stack overflow by catching excessive recursion before system limits are reachedTutorialsPoint - Stack Overflow Prevention | Recursive Depth Tracking
Asked in
Google 15 Microsoft 12 Amazon 8
12.0K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen