HackerRank-Easy-Staircase(Typescript)

Clement
2 min readJun 26, 2022

One warmup exercise before real HackerRank problems. Should be an easy one if you know a bit of Typescript or Javascript. I’ll do it in my way first, and check out how others did latter.

According to the description, we need to create a function which can print a string like this based on the number of the input. (0 < number ≤ 100)

   #
##
###
####

If the input was 4, the function should print a right-aligned staircase composed of #symbols with a height and width of 4.

So here is my steps:

  1. create an empty array arr storing each line of the # we push later.
  2. create a function who accepts the number of length and the identical charactor we want it to iterate as a string by creating an array and joinning all the charactor at the end.
  3. loop over the input n , create and push the new line composed of the prefix of blanks, #s and the suffix of \n into arr.
  4. reduce the arr or join it if you want, and finally, print it.

Here is the code.

At first, I thought this solution was fine, but after I checked out the discussion section, I was blown away. Let’s learn some.

So here is what happened,

  1. We don’t actually need to create “a string” with all the #s inside and print them as a variable. But the testcase let me pass anyway.
  2. Array(n).fill(val, start, end): to create a new array with 3 parameters accepted: the value we want to fill in, the position to start, the position to end.
  3. String.repeat(n): to repeat a string.
  4. String.padStart: to pad the current string with another string.

Alright, that’s all for today.

--

--

Clement

A web frontend developer’s clueless notes that might contain something about Angular, typescript or other frontend related subjects.