Square Matrix of Strings (Hollow Frame)

Coding · Easy · Free problem

Given an integer n ($n \ge 2$), build an n x n square frame and return it as a list of n strings (each of length n). The first and last rows are all '*'; every other row starts and ends with '*' with n - 2 spaces in between.

Complete: ``` frame(n: int) -> List[str] ``` Example: frame(5) returns ['*****', '* *', '* *', '* *', '***']; frame(3) returns ['*', '* *', '***'].

Hints

  1. Three pieces: a full-star top row, n-2 identical interior rows, and a full-star bottom row.
  2. An interior row is '*' + ' '*(n-2) + '*'; for n == 2 there are zero interior rows.

Worked Solution

Assemble the rows directly: a top border, n - 2 interior rows of a star, spaces, and a star, then a bottom border.

```python def frame(n): return ['*' * n] + ['*' + ' ' * (n - 2) + '*'] * (n - 2) + ['*' * n] ```

Complexity $O(n^2)$ characters. For n = 2 there are no interior rows, giving ['', '']. (The original constraint allows n up to

0^6$, but the interesting structure is identical at modest n.)

Intuition

A pure construction problem: the frame is fully determined by border-vs-interior position, so building the three row types directly is both simplest and O(n^2)-optimal.

Open the full interactive solver →