---
title: "Discussion on \"How to Solve the Staircase Problem with 5 Lines of JavaScript\" | Hashnode"
description: "Discussion on \"How to Solve the Staircase Problem with 5 Lines of JavaScript\". Fun with Algorithms"
url: "https://hashnode.com/posts/how-to-solve-the-staircase-problem-with-5-lines-of-javascript/62c8800555f37390f97ca6c5"
---

[Feed](https://hashnode.com/feed) /

Discussion

# [How to Solve the Staircase Problem with 5 Lines of JavaScript](https://indepthjavascript.dev/how-to-solve-the-staircase-problem-with-5-lines-of-javascript?utm_source=hashnode&utm_medium=feed)

Fun with Algorithms

Jul 8, 2022 · 4 min read · indepthjavascript.dev  
Read the article

-   [#javascript](https://hashnode.com/tag/javascript)
-   [#recursion](https://hashnode.com/tag/recursion)
-   [#algorithms](https://hashnode.com/tag/algorithms)
-   [#leetcode](https://hashnode.com/tag/leetcode)

## Written by

[Amit Mehta](https://hashnode.com/@apmfree)

@apmfree · Abington, PA

  
[View profile](https://hashnode.com/@apmfree)

Javascript Developer who Loves to Code!

Self taught full stack developer who loves to code, just for fun. Enjoys health &amp; fitness, yoga, and meditation. Lives with his wonderful wife and 2 cats in Abington, PA.

## Responses 1

Markdown supported · ⌘↵ to post

[Amr Saber](https://hashnode.com/@amr-saber)

[Jul 8, 2022](https://hashnode.com/posts/how-to-solve-the-staircase-problem-with-5-lines-of-javascript/62c8800555f37390f97ca6c5/comment/62c891a355f37390f97ca97a)

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.

[Amit Mehta](https://hashnode.com/@apmfree)

[Jul 8, 2022](https://hashnode.com/posts/how-to-solve-the-staircase-problem-with-5-lines-of-javascript/62c8800555f37390f97ca6c5/comment/62c891a355f37390f97ca97a#reply-62c89f7ce62bf98e0fb0677c)

Yes, excellent point! memo works really well with recursion.

[Amit Mehta](https://hashnode.com/@apmfree)

[Jul 8, 2022](https://hashnode.com/posts/how-to-solve-the-staircase-problem-with-5-lines-of-javascript/62c8800555f37390f97ca6c5/comment/62c891a355f37390f97ca97a#reply-62c8bdc755f37390f97caecf)

Here is the solution to staircase problem using memoization: [indepthjavascript.dev/how-to-solve-the-staircase-…](https://indepthjavascript.dev/how-to-solve-the-staircase-problem-with-javascript-using-memoization)
