Alphabet triangle

Easy TimeO(n²) SpaceO(n²)

Given a row count n, return a triangle whose rows spell "A", "AB", "ABC" and so on, as an array of n strings. Row i holds the first i letters of the alphabet in capitals, starting from A, and n is no larger than 26.

Examples

Example 1

Input
n = 5
Output
A
AB
ABC
ABCD
ABCDE
["A","AB","ABC","ABCD","ABCDE"]
Five rows, and the last of them spells the first five letters.

Example 2

Input
n = 1
Output
A
["A"]
One row, holding the letter the counting starts from.

The Code

function alphabetTriangle(n) {
  const rows = [];
  const A = 65;
  for (let row = 1; row <= n; row++) {
    let line = "";
    for (let col = 0; col < row; col++) {
      line += String.fromCharCode(A + col);
    }
    rows.push(line);
  }
  return rows;
}
alphabetTriangle(5);
Done

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

Step through alphabetTriangle(5) call by call

Explanation

Letters sit in a fixed order, so the ith letter is a fixed distance from A. Counting and spelling are then the same job: a row that counts to i spells i letters without being told which ones.

  1. 1

    A is set to 65, the code for the letter "A". row is 1, and the inner loop counts col from 0 while it is below row, so it runs once: String.fromCharCode(A + 0) gives back "A".

    A
    0

    A=65row=1

    rows.push("A")

  2. 2

    row is 2, so col takes 0 and then 1 and the codes are 65 and 66. Because col starts at 0 rather than 1, the offset added to A is already the distance from the first letter — no adjustment is needed.

    A
    0
    AB
    1

    row=2A + col=65, 66

    rows.push("AB")

  3. 3

    row is 3: codes 65, 66 and 67. Each row spells its letters out again from the start rather than adding one to the row above, so nothing is carried between rows.

    A
    0
    AB
    1
    ABC
    2

    row=3A + col=65 … 67

    rows.push("ABC")

  4. 4

    row is 4 — codes 65 to 68, which is "ABCD".

    A
    0
    AB
    1
    ABC
    2
    ABCD
    3

    row=4A + col=65 … 68

    rows.push("ABCD")

  5. 5

    row is 5 and the codes run 65 to 69, spelling "ABCDE". row++ then fails row <= n and the five strings are returned.

    A
    0
    AB
    1
    ABC
    2
    ABCD
    3
    ABCDE
    4

    row=5A + col=65 … 69

    return rows → 5 rows