Return a Matrix's Elements in Clockwise Spiral Order
Company: Capital One
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Online Assessment
Given an `m x n` matrix of integers, return all of its elements in clockwise spiral order. Start at the top-left element and walk right along the top row, down the rightmost column, left along the bottom row and up the leftmost column; then repeat the same clockwise walk on the remaining inner rectangle, and so on, until every element has been visited exactly once.
### Function Signature
```python
def spiral_order(matrix: list[list[int]]) -> list[int]:
```
### Rules
- Every row of `matrix` has the same length.
- Each element appears exactly once in the output, so the output has `m * n` values.
- When the remaining rectangle is a single row, it is read left to right; when it is a single column, it is read top to bottom.
### Constraints
- `1 <= m, n <= 200`, where `m` is the number of rows and `n` the number of columns.
- `-10^4 <= matrix[i][j] <= 10^4`
### Examples
**Example 1**
- Input: `matrix = [[2, 4, 6], [8, 10, 12], [14, 16, 18], [20, 22, 24]]`
- Output: `[2, 4, 6, 12, 18, 24, 22, 20, 14, 8, 10, 16]`
- Explanation: the outer ring gives `2, 4, 6` (top row), `12, 18, 24` (right column), `22, 20` (bottom row, right to left) and `14, 8` (left column, bottom to top). The remaining inner column `10, 16` is read top to bottom.
**Example 2**
- Input: `matrix = [[5], [-1], [3]]`
- Output: `[5, -1, 3]`
**Example 3**
- Input: `matrix = [[1, 2, 3, 4], [5, 6, 7, 8]]`
- Output: `[1, 2, 3, 4, 8, 7, 6, 5]`
Overview: Return every element of a rectangular integer matrix in clockwise spiral order, starting at the top-left corner and moving inward ring by ring. Tests boundary bookkeeping for non-square shapes, single rows and single columns, and visiting each element exactly once.
Read the full Capital One Software Engineer interview experience this question came from