JavaScript Interview Question – Steps.js

In this article, we have another fun algorithm challenge: steps. It can be a little tricky if you haven’t seen it before, especially since the spaces must be logged to the console. Please try to solve this problem on your own before scrolling down to the solution.

Directions
  • Write a function that accepts a positive number, num.
  • The function should print a step with num levels using the # character.
  • Steps should have spaces on the right-hand side.
Examples
steps(2);

Output:
'# '
'##'

steps(3);

Output:
'#  '
'## '
'###'

Let’s think about how we’re going to do this. See the image below to get a better idea.

Steps algorithm with JavaScript

As per the image above, the first step we’re going to do is write a for loop. We’ll also want to declare a variable to store the spaces and the steps. The first for loop we write is going to iterate through the rows, and the second for loop shall iterate through the columns, deciding if the current column is equal to or less than the current row. If it is, then add a '#'. Else, if it’s not, add a space to the variable declaration. As per the last step, we want to actually console.log() the results (which will be stored in the variable).

Reminder: Before viewing the solution below, try to solve the problem yourself.

Solution

Below is a simple iterative solution, which makes use of two for loops. Can you solve this problem in a different way? Post your solution in the comments below!

function steps(num) {
  for (let row = 0; row < num; row++) {
    let stair = "";

    for (let column = 0; column < num; column++) {
      if (column <= row) {
        stair += "#";
      } else {
        stair += " ";
      }
    }
    console.log(stair);
  }
}
steps(4);
// Output:
// '#    '
// '###  '
// '#### '
// '#####'

Don’t forget to check out Cracking the Coding Interview, where you will learn how to solve algorithmic questions just like this, and lots more!

comments powered by Disqus

Related Posts

Finding Free and Discounted Programming Books

As an avid reader, I’m always looking for places to find my next book. If they’re free, even better. Although it’s not always so easy finding them, there are plenty available online.

Read more

Getting Started with Google Cloud

In this article, we’re going to be taking a first look at Google Cloud, a leading player in the world of cloud computing, offers services and tools designed to drive innovation and ease operations.

Read more

The Great JavaScript Debate: To Semicolon or Not?

Since I’ve started learning this language, JavaScript has undergone some heavy changes. Most notably, it seems to be the norm to not use semicolons anymore.

Read more