Same Number Rows Pattern

beginner Pattern Printing

Problem

Read n and print a triangle where row i contains the number i repeated i times, separated by one space.

Constraints

  • 1 <= n <= 20

Examples

Input

3

Output

1
2 2
3 3 3

Solutions

Best approachTime O(n^2)Space O(1)

The value written in the row is the row number. The inner loop only decides how many times we write it.

Same code works in Java810172125Basic features only, so nothing changes between versions.

Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write " ".repeat(count).

/*
 * Problem : Rows of repeated numbers.
 * Input   : One integer n (rows).
 * Output  : n lines of numbers.
 * Approach: Repeat the row number.
 * Time    : O(n^2)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int rows = new Scanner(System.in).nextInt();

        // Step 1: Repeat once for each row. Row numbers go from 1 to rows.
        for (int row = 1; row <= rows; row++) {
            StringBuilder line = new StringBuilder();

            // Step 2: Write the row number "row" times. Example: row 3 -> 3 3 3.
            for (int count = 1; count <= row; count++) {
                if (count > 1) {
                    line.append(" ");
                }
                line.append(row);
            }

            // Step 3: Print the finished line.
            System.out.println(line);
        }
    }
}
Hints (2)
  1. Use an outer loop for the rows and an inner loop for the numbers in a row.
  2. Write the output for n = 3 and look for the rule.