AlgoViz

Pattern 21

Medium

Hollow square outline

Problem

Print a hollow square outline of stars for a given size n.

In simple words

Use one loop for the rows and another for what goes in each row to draw the shape.

The idea

Print a star only when the cell lies on the border, and a space otherwise. Expressing 'is this cell on the border?' as a single condition on i and j is the point: no special-cased loops are needed.

The trick

  • Border when i == 1 or i == n or j == 1 or j == n.
rows5

Step 1 of 7. Hollow square: print a star only on the border, spaces inside. rows 5.

1/7
Optimal
timeO(n^2)spaceO(1)
1// n = 5 produces:2// * * * * *3// *       *4// *       *5// *       *6// * * * * *7 8for i in 1..n:9  for j in 1..n:10    print (border) ? '*' : ' '

Input

grid
5 × 5

Memory

rows
5

Output

printed rows
rows
5

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Example

Input:
n = 5
Output:
★ ★ ★ ★ ★ / ★ ★ / ★ ★ / ★ ★ / ★ ★ ★ ★ ★

Finished the walkthrough? Add it to your streak.