How to Solve the Staircase Problem with 5 Lines of JavaScript
If you're new to algorithms and leetcode, the staircase problem is infamous!
What is the Staircase Programming Challenge?
Stated simply....
Imagine a staircase with N steps. If you can take 1, 2, or 3 steps at a time, how many different ways can yo...
indepthjavascript.dev4 min read
The complexity of the provided solution is exponential, because you branch 3 times in each recursive call, the complexity is about O(3^n) wich is very bad and will not scale at all for any large N.
A very simple fix is using memoization.
You can change the function a bit to accept the nber of remaining steps, in that case you can think about it as "what's the possible ways to solve x steps" that way you can save the solution to that x in a global map (would be a closure in a real world app) and when you enter the function you check if you already know the solution to x, you just return the value. Pretty much like memoizing the calculation of Fibonacci numbers.