StairCase | HackerRank solution in javascript
Pratik sharma

Pratik sharma @biomathcode

About: Full stack developer

Location:
New delhi
Joined:
Jan 4, 2020

StairCase | HackerRank solution in javascript

Publish Date: Apr 22 '22
9 5

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 : 6

Sample output

     #
    ##
   ###
  ####
 #####
######

Enter fullscreen mode Exit fullscreen mode

Solution in javascript.

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

}
Enter fullscreen mode Exit fullscreen mode

Comments 5 total

  • Rahul Sharma
    Rahul SharmaApr 22, 2022

    padStart also can be used to solve this, for adding padding on string.

    developer.mozilla.org/en-US/docs/W...

    function staircase(n) {
      for (let i = 0; i < n; i++) {
        const line = Array(i + 1)
          .fill("#")
          .join("")
          .padStart(n);
        console.log(line);
      }
    }
    
    Enter fullscreen mode Exit fullscreen mode
  • Muhammad Owais
    Muhammad OwaisAug 17, 2022

    function staircase(n) {
    // Write your code here
    let string = "";
    for (let j = n; j > 0; j--) {
    for (let i = 1; i <= n; i++) {
    if (i < j) {
    string += " ";
    continue;
    }
    string += "#";
    }
    if (j === 1) {
    continue;
    }

    string += "\n";
    
    Enter fullscreen mode Exit fullscreen mode

    }
    console.log(string);

    }

  • Abdellah OUFFA
    Abdellah OUFFANov 13, 2022

    what's the issue with this one!! However, as soon as I run the code on the console it's given me the same output as the one on HackerRank but whenever I sumbit the code through hackerRnak' website ,the compiler message is telling me back the code I wrore was wrong!!
    function drawTriangle(n) {
    let j = "#";
    let i = 1;
    let myTriangle = "";
    while (i <= n) {
    myTriangle += "\n" + j;
    j += "#";
    i++;
    }
    console.log(myTriangle);
    }

  • Amer
    AmerDec 9, 2023

    this for java
    for(int i = 1; i <= n ; i++){
    int freesSpace = n - i ;
    for(int a = 1; a<=freesSpace;a++){
    System.out.print(" ");
    } for(int b = 1; b<=i;b++){
    System.out.print("#");
    }
    System.out.print("\n");
    }
    }

    and all the HackerRan Solution it is in my GitHub
    github.com/Al-Amer/HackerrankJava

Add comment