Two Ways to Solve the HackerRank Staircase Problem in Javascript
If you have studied for software development interviews, then I am sure you have, or will eventually run into the “Staircase” problem where…
- n is an integer denoting the size of the staircase
- print a staircase of size n using # symbols and spaces and make it right-aligned
- Example: n = 4 should print:
At first, I didn’t know where to start so I drew out a staircase with an n = 3 to see if I could identify the patterns and/or relationships between n and the number of spaces in the row. The following is a real picture of the whiteboard that I used to make this discovery:
As you can see…
The first row has n-1 spaces before the #, the second row has n-2 spaces, and the last row has zero spaces.
In terms of the number of hashes (#) in each row, they simply increment by 1 until the row number equals n, in this case, 3.
At this point, I still wasn’t totally sure on how to proceed, but my instincts told me I would need to use at least one for loop — if not 3 — in order to print this out correctly: an outer for loop to keep track of the number of rows, and then two inner for loops to keep track of the spaces and hashes in each row…
Solution A: It works but it ain’t elegant or efficient…
Now that’s a lot of for loops. And this method of solving the problem is very error prone because of all of the variables in each loop…I knew there had to be a better way.
This is when I discovered Javascript’s String.prototype.repeat().
Please see Solution B:
I am no wizard though…it took some time for me to understand how to use .repeat() before I was able to pass the tests on HackerRank again. But it was a great lesson on how to read documentation and then apply it.
I look forward to using .repeat() in more ways!