Generate a Matrix in Spiral Order
Company: Pinduoduo
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's ability to simulate array traversal and manage boundary conditions when filling a matrix in a specific geometric pattern. It tests spatial reasoning, index tracking, and careful loop control, skills commonly assessed in coding interviews focused on array and matrix manipulation. The task requires practical implementation rather than abstract algorithmic theory.
Constraints
- 1 <= m, n <= 100
- The matrix is filled with exactly the integers 1, 2, ..., m * n, each appearing once.
- Traversal order: right across the top, down the right side, left across the bottom, up the left side, repeating while spiraling inward.
- Return the matrix as a list of m rows, each a list of n integers.
Examples
Input: (3, 3)
Expected Output: [[1, 2, 3], [8, 9, 4], [7, 6, 5]]
Explanation: Standard square spiral: 1-3 across the top, 4-5 down the right, 6-7 across the bottom, 8 up the left, 9 in the center.
Input: (3, 4)
Expected Output: [[1, 2, 3, 4], [10, 11, 12, 5], [9, 8, 7, 6]]
Explanation: Rectangular (more columns than rows). After the outer ring, the inner 1x2 strip is filled 11, 12.
Input: (1, 4)
Expected Output: [[1, 2, 3, 4]]
Explanation: Single row — only the top-row pass runs; the guards prevent the bottom/left passes from re-filling cells.
Input: (4, 1)
Expected Output: [[1], [2], [3], [4]]
Explanation: Single column — top-row fills [0][0], then the right-column pass fills the rest going down.
Input: (1, 1)
Expected Output: [[1]]
Explanation: Minimum matrix — a single cell gets value 1.
Input: (2, 2)
Expected Output: [[1, 2], [4, 3]]
Explanation: Smallest full ring exercising all four directions: right (1,2), down (3), left (4).
Hints
- Maintain four boundaries — top, bottom, left, right — and shrink them inward after completing each edge of the current layer.
- Fill one direction at a time in the loop: top row left→right, right column top→bottom, bottom row right→left, left column bottom→top.
- After walking the top row, increment top; after the right column, decrement right; and so on. Re-check the guards (`if top <= bottom`, `if left <= right`) before the bottom row and left column to avoid double-filling on thin (single-row or single-column) matrices.
- The outer loop condition `top <= bottom and left <= right` stops once every cell is filled.