DEV Community

Cover image for StairCase | HackerRank Solution in JavaScript
Christotle Agholor
Christotle Agholor

Posted on

StairCase | HackerRank Solution in JavaScript

Let's look at the Problem Statement :

Input Format
A single integer, n, denoting the size of the staircase.

Constraints: 0 < n <= 100

Output Format :

Print a staircase of size using # symbols and spaces.

Note: The last line must have spaces in it.

Example:
Sample Input : 4

Sample output

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

Solution 1. in JavaScript.

function staircase(n) {
    // Write your code here
    let str = '';
    for(let i = 1; i < n + 1; i++) {
        str += Array(n - i).fill(' ').join('')
        str += Array(i).fill('#').join('')
        console.log(str)
        str = ''
    }

}
Enter fullscreen mode Exit fullscreen mode

Solution 2. in JavaScript.

function staircase(n) {
  for (let i = 0; i < n; i++) {
    let str = Array(i + 1)
      .fill("#")
      .join("")
      .padStart(n);
    console.log(str);
  }
}
Enter fullscreen mode Exit fullscreen mode

OR

// without the padStart it will still give same result.

function staircase(n) {
  for (let i = 0; i < n; i++) {
    let str = Array(i + 1)
      .fill("#")
      .join("")
     console.log(str);
  }
}
Enter fullscreen mode Exit fullscreen mode

but in this case, the element flows to the left

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

Top comments (1)

Collapse
 
johnchristotle profile image
Christotle Agholor

Great one from me. This is my first post and I believe it is the begining of good things to come for all my javascript enthusias.