Print a Rectangle Star Pattern

Solve this Problem
Easy5 min
Topics
Companies
Given two integers rows and cols, return a rectangle of stars — rows rows, each cols stars wide. This is the Square Star Pattern problem generalized to independent row and column counts. Both solutions carry over directly: the nested loopsNested LoopsAn outer loop over rows, an inner loop appending one character at a time to build each row. version just uses cols instead of n for the inner bound, and the string repetitionString RepetitionBuilding the repeated row once with a built-in, then repeating that row rows times. version builds the cols-wide row once and repeats it rows times.

Test Case 1:

Input:rows = 2, cols = 4
Output:["****", "****"]
Explanation:2 rows, each 4 stars wide.

Test Case 2:

Input:rows = 1, cols = 1
Output:["*"]
Explanation:A single star.

Constraints

  • ◆1 ≤ rows ≤ 20
  • ◆1 ≤ cols ≤ 20

Try the Dry Run

Approach & Solutions

Nested Loops — Print Each CharacterGood

For each of the rows rows, run an inner loop that appends a '*' exactly cols times, then collect the finished row — the same two-dimension-matching nested loop as a square, just with independent row and column counts.

TimeO(rows × cols)
SpaceO(rows × cols) for the output
1class Solution { 2 public String[] printRectanglePattern(int rows, int cols) { 3 String[] result = new String[rows]; 4 for (int i = 0; i < rows; i++) { 5 StringBuilder row = new StringBuilder(); 6 for (int j = 0; j < cols; j++) { 7 row.append('*'); 8 } 9 result[i] = row.toString(); 10 } 11 return result; 12 } 13}
String RepetitionOptimal

Every row is identical, so build the cols-wide row once with a built-in repeat, and repeat THAT rows times. C has no string-repeat built-in, so it keeps the explicit loop.

TimeO(rows × cols)
SpaceO(rows × cols)
1class Solution { 2 public String[] printRectanglePattern(int rows, int cols) { 3 String[] result = new String[rows]; 4 for (int i = 0; i < rows; i++) { 5 result[i] = "*".repeat(cols); 6 } 7 return result; 8 } 9}

Related Problems