Print a Square Star Pattern
Solve this ProblemEasy5 min
Topics
BasicsPatternsLoops
Companies
TCSInfosysWipro
Given an integer
n, return the n rows of an n×n block of stars — every row is a string of n asterisks.
The nested loopsNested LoopsAn outer loop over rows, and an inner loop that appends one character at a time to build each row. version builds every row character by character — the direct way to think about a grid: n rows, n columns each. The string repetitionString RepetitionA built-in operation that produces a string of a repeated character directly, without an explicit inner loop. version recognizes that every row here is identical, and hands that repetition off to a built-in — still the same O(n²) total output, just without writing the inner loop by hand.
Test Case 1:
Input:n = 3
Output:["***", "***", "***"]
Explanation:A 3×3 block of stars — every row is identical.
Test Case 2:
Input:n = 1
Output:["*"]
Explanation:A single star.
Constraints
- ◆
1 ≤ n ≤ 20
Try the Dry Run
Approach & Solutions
Nested Loops — Print Each CharacterGood
For each of the n rows, run an inner loop that appends a '*' exactly n times, then collect the finished row. Two nested loops, exactly matching the two dimensions of the square.
Time
O(n²)Space
O(n²) for the outputJava
1class Solution {
2 public String[] printSquarePattern(int n) {
3 String[] result = new String[n];
4 for (int i = 0; i < n; i++) {
5 StringBuilder row = new StringBuilder();
6 for (int j = 0; j < n; j++) {
7 row.append('*');
8 }
9 result[i] = row.toString();
10 }
11 return result;
12 }
13}String RepetitionOptimal
Every row in a square is identical, and many languages can build a repeated-character string directly — no inner loop needed at all. C has no such built-in, so it keeps the explicit character-by-character loop.
Time
O(n²)Space
O(n²)Java
1class Solution {
2 public String[] printSquarePattern(int n) {
3 String[] result = new String[n];
4 for (int i = 0; i < n; i++) {
5 result[i] = "*".repeat(n);
6 }
7 return result;
8 }
9}