Print a Number Square Pattern

Solve this Problem
Easy5–10 min
Topics
Companies
Given an integer n, return the n rows of a number square — row i is the number i, repeated n times and separated by single spaces. The nested loopsNested LoopsAn outer loop over rows, an inner loop appending the row number n times, with spaces between repeats. version builds each row number by number. The join/repeatBuild with Join / RepeatDescribing the row directly as "the string i, repeated n times, joined by spaces" — a single expression in most languages. version says exactly that in one expression, skipping the inner loop in every language with that built-in available.

Test Case 1:

Input:n = 3
Output:["1 1 1", "2 2 2", "3 3 3"]
Explanation:Row i is the number i, repeated n times, space-separated.

Test Case 2:

Input:n = 1
Output:["1"]
Explanation:A single row, a single number.

Constraints

  • ◆1 ≤ n ≤ 9

Try the Dry Run

Approach & Solutions

Nested Loops — Print Each NumberGood

For row i, run an inner loop n times, appending the number i each time — with a space in front of every number after the first, so the row reads as space-separated digits rather than one run-together number.

TimeO(n²)
SpaceO(n²) for the output
1class Solution { 2 public String[] printNumberSquare(int n) { 3 String[] result = new String[n]; 4 for (int i = 1; i <= n; i++) { 5 StringBuilder row = new StringBuilder(); 6 for (int j = 1; j <= n; j++) { 7 if (j > 1) row.append(' '); 8 row.append(i); 9 } 10 result[i - 1] = row.toString(); 11 } 12 return result; 13 } 14}
Build with Join / RepeatOptimal

Row i is just the string "i" repeated n times, joined by spaces — a direct description that most languages can build with a single repeat-and-join call, no inner loop needed. C has no such built-in, so it keeps the explicit double loop.

TimeO(n²)
SpaceO(n²)
1class Solution { 2 public String[] printNumberSquare(int n) { 3 String[] result = new String[n]; 4 for (int i = 1; i <= n; i++) { 5 result[i - 1] = String.join(" ", Collections.nCopies(n, String.valueOf(i))); 6 } 7 return result; 8 } 9}

Related Problems