How would you write code to generate a spiral matrix using a 2D array?
What the interviewer wants to learn
- Your ability to translate a problem description into clear, correct code.
- Understanding of array indexing, loops, and boundary management.
- Awareness of time and space complexity, and how you handle edge cases (e.g., empty matrix, non‑square dimensions).
- Communication style: can you explain your approach step‑by‑step?
How to structure your answer
1. **Clarify the requirements** – size of the matrix, start direction, clockwise vs. counter‑clockwise.
2. **Outline the algorithm** – describe the “layer‑by‑layer” filling strategy and how you’ll track the current boundaries (top, bottom, left, right).
3. **Walk through a small example** (e.g., 3×3) to show the filling order.
4. **Present the code** – keep it concise, use meaningful variable names, and comment the main steps.
5. **State the complexity** – O(n²) time, O(n²) space for the matrix, O(1) extra space.
6. **Mention edge cases** – n = 0, n = 1, and how the loop terminates.
Example answer
“Sure, I’d start by confirming that we need an *n × n* matrix filled clockwise, starting at the top‑left corner with 1. The common way is to fill the matrix layer by layer. I’ll keep four pointers: `top`, `bottom`, `left`, and `right`. While `top <= bottom` and `left <= right`, I’ll:
1. Fill the top row from `left` to `right`, then increment `top`.
2. Fill the right column from `top` to `bottom`, then decrement `right`.
3. If there’s still a row left, fill the bottom row from `right` to `left`, then decrement `bottom`.
4. If there’s still a column left, fill the left column from `bottom` to `top`, then increment `left`.
Each step writes the next integer and advances a counter. When the pointers cross, we’re done. Here’s a quick Python implementation:
def generate_spiral(n):
if n <= 0:
return []
matrix = [[0] * n for _ in range(n)]
top, bottom = 0, n - 1
left, right = 0, n - 1
num = 1
while top <= bottom and left <= right:
# top row
for c in range(left, right + 1):
matrix[top][c] = num
num += 1
top += 1
# right column
for r in range(top, bottom + 1):
matrix[r][right] = num
num += 1
right -= 1
# bottom row
if top <= bottom:
for c in range(right, left - 1, -1):
matrix[bottom][c] = num
num += 1
bottom -= 1
# left column
if left <= right:
for r in range(bottom, top - 1, -1):
matrix[r][left] = num
num += 1
left += 1
return matrix
The algorithm visits each cell exactly once, so the time complexity is O(n²) and the extra space beyond the output matrix is O(1). It also works for `n = 1` and returns an empty list for `n = 0`.
Mistakes to avoid
- **Skipping boundary checks** after each side; forgetting the `if top <= bottom` / `if left <= right` guards leads to duplicate writes on odd‑sized matrices.
- **Using mutable default arguments** or global variables that retain state between calls.
- **Misreporting complexity** – the algorithm is linear in the number of cells, not quadratic in the loop count.
- **Hard‑coding dimensions**; the solution should work for any positive integer `n`.
- **Over‑engineering** – a recursive approach is possible but adds unnecessary overhead for this simple task.