DEV Community

Cover image for Staircase Challenges: Repeat, Iteration, and Recursion Strategies
Jesse Smith Byers
Jesse Smith Byers

Posted on • Edited on

Staircase Challenges: Repeat, Iteration, and Recursion Strategies

This next series of code challenges all have to do with arranging elements in a matrix pattern, and printing out the results. Each can be solved in multiple ways, using iteration or recursion. We'll start with staircase patterns in this post, but stay tuned for others in future posts. Let's jump in!

1. Building a Staircase

In variations of this problem, you are asked to print out the shape of a staircase with n levels. For an example, you can check out the Staircase Problem on HackerRank. Some challenges may ask you to print out the steps facing right, left, or even upside down, but a similar strategy can be used for each variation. It this example, we are given a number of levels, n, and are asked to print out a staircase with n levels ascending from left to right, like this:

staircase(4)

// Result:

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

Possible Strategies

The first key to solving this problem through any of the strategies involves visualizing an example of the staircase and breaking it down into a matrix of spaces and symbols, like so:

Row 0 Row 1 Row 2 Row 3
Col 0 #
Col 1 # #
Col 2 # # #
Col 3 # # # #

If n=4, we would have 4 rows and 4 columns total. There would be 4 symbols in the bottom row, and zero spaces. Seeing the rows and columns visually can help us get down to coding.

String Repeat Strategy

The most concise solution to this problem uses a single loop to iterate through the rows, and build out a string using the repeat method.

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

While this may work with easier variations of the staircase problem, it would likely break down with more complex challenges, so it is important to know the iteration and recursion strategies below.

Iteration Strategy

Since the symbol placement is dependent on a location based on rows and columns, we can use iteration through the rows and columns to start our solution. We will print each line to the console based on rows, but will arrange symbols within each row by paying attention to the columns. Therefore, we can start pseudo-coding our solution like this:

// function staircase(n) {
  // iterate through rows {
    // set up empty string for the given row

    // iterate through columns {
      // if the column number is less than or equal to the row 
        // add # to the end of the string
    // otherwise
      // add an empty space to the beginning of the string
    // }

    // console.log the string for the row
  // }
// }
Enter fullscreen mode Exit fullscreen mode

Next, we can code it out underneath our notes:

function staircase(n) {
    // iterate through rows
    for (let row = 0; row<n; row++) {
      // set up empty string for the given row
      let string = ""

        // iterate through columns
        for (let column = 0; column<n; column++) {
            // if the column number is less than or equal to the row 
            if (column <= row) {
              // add # to the end of the string
              string = string + "#"
            } else {
              // add an empty space to the beginning of the string
              string = " " + string
            }
        }
        // console.log the string for the row
        console.log(string)
    }
}
Enter fullscreen mode Exit fullscreen mode

Complete code without the comments:

function staircase(n) {
    for (let row = 0; row<n; row++) {
      let string = ""

        for (let column = 0; column<n; column++) {
            if (column <= row) {
              string = string + "#"
            } else {
              string = " " + string
            }
        }
        console.log(string)
    }
}

staircase(4) => //

   #
  ##
 ###
####

Enter fullscreen mode Exit fullscreen mode

Recursion Strategy

In this strategy, we will still use the matrix diagram to help us visualize the rows and columns that make up the staircase.

Row 0 Row 1 Row 2 Row 3
Col 0 #
Col 1 # #
Col 2 # # #
Col 3 # # # #

However, instead of iterating through the rows and columns, we will call the staircase function for each row, and will build out a string to represent each row based on the number of columns in the matrix.

In pseudo-code, here is what we will need to do:

// set default values for arguments that will be needed in each function call (row number, and string)

  // set up a base case so that the recursive function calls will stop (when n reaches zero)


  // set up a conditional to account for the cases when the string length for a row is full (n===string.length)

      // print out the row (string)

      // call the function to start work on the next row (row + 1)


  // account for adding characters to the string if the row is not yet full (n < string.length), based on comparing the string length with the row number

  // call the function to continue working on the row, with the current row and updated string passed as arguments
Enter fullscreen mode Exit fullscreen mode

In code, we end up with:

function staircase(n, row=0, string="") {
    if (n===row) {
        return
    }

    if (n===string.length) {
        console.log(string)
        return staircase(n, row+1)
    }

    const add = string.length <= row ? "#" : " "
    staircase(n, row, add + string)
}
Enter fullscreen mode Exit fullscreen mode

Applying the Strategies to Other Variations

In order to solve similar staircase challenges with slightly different variations, you likely will just need to change small details in your code. Draw out the expected output into rows and columns, and ask yourself these questions:

  • What line/lines would I need to change to flip the direction of the steps (left or right, or top or bottom)?
  • What line/lines would I need to change to alter the number, arrangement, or patterns of symbols and spaces in each row?

Using similar strategies, you should be able to figure out pyramid challenges, such as this one:

Write a function that will take in one parameter, the height of a pyramid, and will print out the shape of a pyramid with that many levels.

For example, pyramid(4) would result in the output:

   x  
  xxx
 xxxxx
xxxxxxx
Enter fullscreen mode Exit fullscreen mode

Have you seen other variations on the Staircase or Pyramid Problems? Share them below!

Top comments (0)