The Staircase Problem

Mike Archer
2 min readJan 3, 2021

--

After graduating from Flatiron, I have found myself doing hour after hour of algorithm practice to help me land a job. I wanted to write this blog about one of the simpler ones that I very much enjoyed solving.

This particular problem is a great jumping off point, as it is fairly basic but has some great quirks involved.

For me, I found what helped me crack this problem was to actually draw out what they requested.

Assuming our n = 4:

_ _ _ #

_ _ # #

_ ###

####

After drawing this out, I understood that I would need multiple for loops to make this work.

First, we start by defining ‘string’, which will be our return at the end.

The first for loop (let i =1; i ≤ n ; i++) is responsible for setting up the number of rows. This loop starts at 1 and increments by 1 each time, creating a new row by adding “\n” after each iteration.

The next loop (for s = n-1; s ≥ i; s- -) is going to set up the “_” before the “#”. This starts at n-1 so that the first row will have the proper amount of “_” to begin the pattern. By decrementing at the end of each loop, we create the staircase effect.

Our final loop (let h =1; h≤ i; h ++) is responsible for adding the correct number of “#” to our string. Notice that each of the last two loops are nested within our first loop, however these are on the same level. This starts at 1 because the top row will always have one “#” and increase once per row. By setting this to be ≤ i we ensure that our loop will end at the proper time.

This is undoubtedly not a perfect solution, and I am sure there is a much simpler one liner out there somewhere, but I hope you find this guide helpful!

--

--

No responses yet