2 min to read
Staircase - HackerRank Problem Solving
Staircase is a Hackerrank problem from Algorithms subdomain that requires the understanding of loops and string manipulation. In this post, you will learn how to solve Hackerrank’s Staircase problem and its solution in Python and C++.
Problem Statement and Explanation
Basically, we have to print a staircase of size n. The staircase should be right-aligned, composed of # symbols and spaces, and has a height and width of n.
Input Format
- A single integer, n, denoting the size of the staircase.
Output Format
- Print a staircase of size n using # symbols and spaces.
Staircase Solution in Python
Explanation of Solution in Python
- The
staircase()
, which takes an integern
as input and prints a staircase of sizen
. - The
staircase()
function works by iterating from 1 ton
and printing a line of hashtags on each iteration. The number of hashtags printed on each line is equal to the current iteration number. The line is right-aligned using the:>
format specifier. -
The
main()
function prompts the user to enter the size of the staircase and then calls thestaircase()
function to print the staircase. for i in range(1, n + 1):
This line of code iterates from 1 to n.print(f'{"#"*i:>{n}}'):
This line of code prints a line ofi
hashtags, right-aligned to n characters. Thef
prefix indicates that this is a formatted string. The{"#"*i}
expression evaluates to a string ofi
hashtags. The:>{n}
format specifier indicates that the string should be right-aligned ton
characters.
Staircase Solution in C++
Explanation of Solution in C++
- It includes the
bits/stdc++.h
header file, which provides access to all the standard C++ libraries. - It defines a function called
staircase()
, which takes an integern
as input and prints a staircase of sizen
. - The
staircase()
function works by iterating from0
ton-1
and printing a line of hashtags on each iteration. The number of hashtags printed on each line is equal to the current iteration number plus one. - The number of spaces printed before the hashtags on each line is equal ton
minus the current iteration number minus one. This ensures that the staircase is printed in the correct shape. -
The
main()
function prompts the user to enter the size of the staircase and then calls thestaircase()
function to print the staircase. cout << setfill(' ') << setw(n-(i+1)) << "";:
This line of code printsn
minus the current iteration number minus one spaces.cout << setfill('#') << setw(i+1) << '#'<< endl;:
This line of code prints the current iteration number plus one hashtags.endl;:
This line of code prints a newline character.