Right-angled star triangle

Easy TimeO(n²) SpaceO(n²)

Given a row count n, return a right-angled triangle of stars as an array of n strings, one per row. Row 1 holds a single *, row 2 holds two, and row n holds n of them. The left edge is flush: no row carries leading padding, so the stars of every row begin in the same column.

Examples

Example 1

Input
n = 5
Output
*
**
***
****
*****
["*","**","***","****","*****"]
Five rows widening by one star each time, so the last of them holds five.

Example 2

Input
n = 1
Output
*
["*"]
One row, and row 1 holds one star.

The Code

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

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

Step through rightTriangle(5) call by call

Explanation

A row’s width is the row’s own number. Nothing carries from one row to the next, so the shape is decided by where the counting stops on each one.

  1. 1

    row is 1. line starts as the empty string, and the inner loop runs while col is at most row — so once, appending one *. rows.push(line) stores the finished string.

    *
    0

    row=1rows.length=0

    rows.push("*")

  2. 2

    row is 2, and the inner bound is row rather than a number, so it moves with it: two passes, line becomes "**".

    *
    0
    **
    1

    row=2rows.length=1

    rows.push("**")

  3. 3

    row is 3 — three passes, three stars. Nothing is carried over from the row before, because line is declared inside the outer loop and starts empty again.

    *
    0
    **
    1
    ***
    2

    row=3line=""

    rows.push("***")

  4. 4

    row is 4, so col runs 1, 2, 3, 4 and four stars go on.

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

    row=4rows.length=3

    rows.push("****")

  5. 5

    row is 5: five passes, five stars. row++ then makes it 6, which fails row <= n, so the outer loop ends and the five strings in rows are handed back.

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

    row=5rows.length=4

    return rows → 5 rows