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

Creating a Real Time Chat Application with React, Node, and TailwindCSS

In this tutorial, we will show you how to build a real-time chat application using React and Vite,as well as a simple Node backend.

Read more

The Importance of Staying Active as a Software Developer

In today’s fast-paced digital world, developers often find themselves glued to their screens for extended periods. While this dedication is commendable, it comes with its own set of challenges.

Read more

JavaScript DOM Mastery: Top Interview Questions Explained

Mastering the Document Object Model (DOM) is crucial for any JavaScript developer. While many developers rely heavily on front-end frameworks, the underlying DOM concepts are still important.

Read more