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

Unveiling the Fascination of the Collatz Conjecture: Exploring Sequence Creation with JavaScript

The Collatz Conjecture, also known as the 3x+1 problem, is a fascinating mathematical puzzle that has intrigued mathematicians for decades. It has sparked publications with titles such as The Simplest Math Problem Could Be Unsolvable, or The Simple Math Problem We Still Can’t Solve because it is, indeed, rather simple-looking.

Read more

The Art of Data Visualization: Exploring D3.js

Data is everywhere, flowing into our applications from various sources at an unprecedented rate. However, raw data alone holds little value unless it can be transformed into meaningful insights.

Read more

JavaScript’s Secret Weapon: Supercharge Your Web Apps with Web Workers

During an interview, I was asked how we could make JavaScript multi-threaded. I was stumped, and admitted I didn’t know… JavaScript is a single-threaded language.

Read more