Saturday 5 September 2015

Staircase Problem



This is one of the common problems encountered while studying Algorithms .
Problem : Input 'N' as the height of the Staircase , Draw a Staircase with the given Height.
Input : 4
Output : 
   #
  ##
 ###
####

Before coding , analysis of Input and Output:

  1. Total no. of lines in output is equal to height of the staircase.
  2. No. of hashes ‘#’ in last line is equal to the height of staircase.
  3. In output,line 1 has 1 hash,line 2 has 2 hashes and so on… so to print this pattern we have to print blank space ” “ before hashes which will be equal to the value obtained by subtracting the line number or number of hashes from the height of the staircase.
Note : Code samples are written in C++ , if anyone faces any problem in the code then please comment in the comments section.

Solution 1 :

Time Complexity : O( N)

Another Approach (using string)


In the above code, setW(int n) is used to set the width of the output stream.<iomanip> needs to be included to use this function.
.

Solution 2:

Time Complexity : O(N)


in the above code, s.push_back('#') : push_back (char c) is used to Append character to string.

Another Approach ( taking advantage of String Initialization )



Conclusion

There can be many solutions to a same problem . It totally depends on you how do you think about it. If you have any other solution ,then please comment in the comments section.
Learn and share it with others.

Feedback is always Welcome.Keep Coding !!!