DEV Community

Cover image for The Staircase problem (a JavaScript solution)
Andrea
Andrea

Posted on

The Staircase problem (a JavaScript solution)

What is the infamous staircase problem?

Imagine a staircase. Each step takes you further from the first one. Simple enough, right?

The base and height both equal n; # symbols and spaces represent each level of stairs. Your code should return a staircase of n size.

Conditions

  • n is an integer that represents the size of the staircase ie: n = 3
  • Print the staircase size with spaces and #.
  • sample:
     #
    ##
   ###
Enter fullscreen mode Exit fullscreen mode

Start Simple

We know that as we travel down the staircase, we need to reduce the number of spaces by 1. We also needed to keep track of each row to reduce the number of spaces.

Let's start with something simple(and ugly)...

function staircase(n) {
   let row = "";

   for (let j = n; j > 0; j--) {
      for (let i = 1; i <= n; i++) {
         if (i < j) {
            row += " ";
            continue;
         }
            row += "#";
         } if (j === 1) {
            continue;
         }
      row += "\n";
      }
   console.log(row);
}
Enter fullscreen mode Exit fullscreen mode

The break down:

  1. I created a variable called row that will return the final result
  2. The first(outer) loop tracks the number of rows n, that we need.
  3. The second (inner) loop, tracks the number of spaces and # symbols needed for each row.
  4. Lastly, we output the result with a console.log.

The refactor

While the above code meets all the problem requirements, it's messy. So I did some research and found a much cleaner solution by Ali Reubenstone that uses JavaScript's repeat method.

function staircase(n) {
    for (let i = 1; i <= n; i++) {  
        console.log(" ".repeat(n-i) + "#".repeat(i))
    }    
}
Enter fullscreen mode Exit fullscreen mode

Let's break it down:

  1. The for loop iterates over each row.
  2. During the interation process, we print the # symbols and spaces.
  3. Finally, we repeat the blank spaces by the n-i number and # symbols by 'i' number of times so that each row (from top to bottom) reduces the number of spaces while increasing the number of # symbols, thus creating a staircase shape.

Top comments (0)