Inverted star triangle

Easy TimeO(n²) SpaceO(n²)

Given a row count n, return an inverted right-angled triangle of stars as an array of n strings. The first row holds n stars and every row after it holds one fewer, so the last row holds a single *. The left edge is flush: the rows all begin in the same column and lose their stars from the right.

Examples

Example 1

Input
n = 5
Output
*****
****
***
**
*
["*****","****","***","**","*"]
Five rows starting at five stars and losing one each time.

Example 2

Input
n = 1
Output
*
["*"]
One row, which is both the widest and the narrowest, so it holds one star.

The Code

function invertedTriangle(n) {
  const rows = [];
  for (let row = n; row >= 1; row--) {
    let line = "";
    for (let col = 1; col <= row; col++) {
      line += "*";
    }
    rows.push(line);
  }
  return rows;
}
invertedTriangle(5);
Done

The first 17 calls, of 27. This one does not fit on a page.

Step through invertedTriangle(5) call by call

Explanation

The widths are the growing triangle’s, 1 through n, handed out in the opposite order. Only the order the rows are counted in changes, so nothing inside a row has to.

  1. 1

    row starts at n rather than 1, and the inner bound is still row, so the very first row is the widest: five passes, five stars.

    *****
    0

    row=5rows.length=0

    rows.push("*****")

  2. 2

    row-- takes it to 4, which is still at least 1, so the outer loop runs again. The inner loop follows it down to four passes.

    *****
    0
    ****
    1

    row=4rows.length=1

    rows.push("****")

  3. 3

    row is 3. Only the direction of the outer count has changed — the body building line is the same one the growing triangle uses.

    *****
    0
    ****
    1
    ***
    2

    row=3line=""

    rows.push("***")

  4. 4

    row is 2, so col runs 1 and 2 and two stars go on.

    *****
    0
    ****
    1
    ***
    2
    **
    3

    row=2rows.length=3

    rows.push("**")

  5. 5

    row is 1: one pass, one star. row-- then makes it 0, which fails row >= 1, so the loop ends on the narrowest row instead of the widest.

    *****
    0
    ****
    1
    ***
    2
    **
    3
    *
    4

    row=1rows.length=4

    return rows → 5 rows