Javascript Steps Problem

The goal of this problem is to take in a number (example – 4, and then print out that number of steps).  There must be a space to pad out the rest of the character.  Ex. n=4; loop 1 will be one # and three spaces for a total of 4 characters:

I’m still working through Grider’s Udemy course on interview questions.  First I did it my own way that used two nested for loops.  I create an array called “step.”  Variable i loops through the number passed to the function (n=4 in the above illustration).  Variable j loops through and pushes the “#” symbol to the array based on the value of i.  Then the variable k loops through n-i times and pushes a ” ” to the array “step.”  Lastly, I use the join(“”) method to console log a string.  It’s not elegant, but it works.

Option 2 –  This is a much simpler solution that uses a nested loop with the outside loop representing rows and the inside loop representing columns.  This looks at the problem as a grid.  If the column is <= row, it outputs a “#” otherwise, it outputs a ” “(blank space).

Option 3 – Recursive Solution


Leave a Reply

Your email address will not be published. Required fields are marked *