DEV Community

David
David

Posted on

HackerRank JS: Solving the Staircase Problem in JavaScript

Recently, I tackled a fun coding challenge: building a right-aligned staircase with a given height n, using JavaScript. I wanted to share how I approached and solved this problem, hoping it might help others tackle similar challenges.

The task: Print a staircase of height n where the # symbol represents each step. The tricky part is that the steps are right-aligned, and the rest of the row is filled with spaces.

For example, given n = 4, we need the output to look like this:

   #
  ##
 ###
####
Enter fullscreen mode Exit fullscreen mode

At first glance, it might look like a simple nested loop problem, but the alignment requires careful attention to how we place spaces and # symbols.

Thought Process:
Before jumping into code, I broke the problem into smaller, manageable tasks:

Print n rows: Each row should represent a step in the staircase.
Each row has exactly n characters: Some of them are spaces, and the rest are #.
Spaces should come before #: As the row number increases, fewer spaces are needed, and more # symbols are added.

Plan:
For every row i (starting from 0):
Add spaces for the first n - i - 1 characters (to ensure right alignment).
Then, fill the rest of the row with # characters.
The logic is that as i (the row number) increases, the number of spaces decreases, and the number of # symbols increases.

The Solution Code:
Here’s the code I wrote to implement this plan:

function staircase(n) {
    // Write your code here
      var height = n;

    for (let i=0; i < height; i++) {
        let row= "";
        for (let j=0; j < height; j++) {
            if (i + j > height - 2) {
                row += "#";
            } else {
                row +=  " ";
            }
        }
        console.log(row)
    }
}
Enter fullscreen mode Exit fullscreen mode

How It Works:

  • Initialize the height: The first thing we do is store the value of n in the height variable. This makes the code easier to read and understand.

  • Outer loop: This loop runs n times, representing the rows of the staircase. Each iteration corresponds to a row in the final output.

  • Inner loop: This loop runs n times as well, controlling how many characters will be in each row.

  • Condition to add # or space: The condition if (i + j > height - 2) checks whether a # should be printed. If this condition is met, we append a # to the row; otherwise, we add a space. This ensures that for each row, spaces appear first and then the # symbols.

  • Print the row: Once a full row is constructed (a mix of spaces and # symbols), it is printed to the console.

Top comments (0)