Start learning free

LESSON 175 OF 348 · STRINGS

Print Triangle of Stars in TypeScript

Practice O(n2) Read the full explanation

Given a positive integer n print a triangle of stars as in the example below

Example:

Input: n = 5
Output:
*
**
***
****
*****
Explanation: Print 5 lines, on ith line print i stars.
STEP 1 OF 4
    Ctrl + Enter to check

    TYPESCRIPT · STRINGS

    Print Triangle Of Stars in TypeScript, explained

    Problem overview

    The method printStars receives a positive integer n and prints a triangle made of stars. It prints n lines, and line number i (counting from 1) holds exactly i stars. It returns nothing, which is why its return type is void: the output is what the method prints, not a value it hands back.

    For n = 5, the output is:

    *
    **
    ***
    ****
    *****
    

    Approach: grow one row into the next

    You could build every row from scratch, but there is a simpler observation: each row is the previous row plus one more star. Row 3 is row 2 with a star added at the end.

    So keep one string, str, that starts empty. Repeat n times: add a star to str, then print it. The first pass prints one star, the second prints two, and so on. No counting of stars is needed, because the string itself carries the count.

    Step by step

    1. Declare the row. Create str with let, because it changes on every pass. Give it the type string and start it as "".
    2. Loop once per row. Write for (let i = 0; i < n; i++). It runs exactly n times, for i equal to 0, 1, ..., n - 1. The counter i only counts the rows. Its value is never used inside the loop.
    3. Add a star. Inside the loop, str += "*" appends one star to the end of the current row.
    4. Print the row. Still inside the loop, after the star was added, call console.log(str). Each call ends the line, so every row gets its own line. Printing before adding the star would make the first row empty, and printing after the loop would show only the last row.

    The solution in TypeScript

    class Solution {
        printStars(n: number): void {
            let str: string = "";
            for (let i = 0; i < n; i++) {
                str += "*";
                console.log(str);
            }
        }
    }
    

    The TypeScript details worth a closer look:

    • void means no result. The method has no return. The printing happens as a side effect of console.log. Calling new Solution().printStars(3) prints three lines.
    • number for every number. The parameter n is a number, the one numeric type used for integers and decimals alike. The loop works as the statement intends for whole numbers.
    • += on a string. The right side is joined to the end of the old string, and the new string is stored in str. Strings are immutable, so a new string is created each time. For rows this short, that is no concern.
    • let and const. str is reassigned, so it needs let. The loop counter is also declared with let because i++ reassigns it.
    • console.log adds the line break. You don't write "\n" yourself. The string you pass has no line break in it, and each call prints its argument followed by a new line.

    Complexity

    Time: O(n²). The loop runs n times, and printing the row on pass k writes k characters. The total number of characters printed is 1 + 2 + ... + n, which is n(n + 1) / 2. Any solution has to print that many stars, so the quadratic time comes from the size of the output.

    Space: O(n). The only thing stored is str, which grows to n characters.

    Edge cases and common mistakes

    • n = 1. The loop runs once and prints a single *.
    • Printing after the loop. Only the last row, ***** for n = 5, is shown.
    • Printing before adding the star. The first line is empty, and the last row is missing.
    • Resetting str inside the loop. If the declaration sits inside the loop, every row has just one star.
    • Off-by-one bounds. i <= n with i starting at 0 prints n + 1 rows.
    • Returning a string instead of printing. The method's return type is void, and the lesson's tests look at what is printed.

    Testing

    • n = 1 prints one line: *.
    • n = 3 prints *, **, ***, each on its own line.
    • n = 5 prints the triangle from the example.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free