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.
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!
Related Posts
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 moreHacktoberfest 2024: Get a Free JavaScript Today Sticker
October is here, and that means one thing in the tech world—Hacktoberfest! This annual event, powered by DigitalOcean, Cloudflare, Quira, and other sponsors, encourages developers of all skill levels to contribute to open-source projects.
Read moreCreating 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