Question presented to candidate: "Given an m by n matrix as a Python list of lists, return all of its elements in spiral order: start at the top-left, go right along the top, down the right side, left along the bottom, up the left side, and keep going inward."
What a strong answer should cover:
- Four boundaries (
top,bottom,left,right) that shrink after each side is walked; loop whiletop <= bottom and left <= right. - The two guards before the bottom row and the left column, which stop a single remaining row or column from being read twice.
- O(m·n) time, O(1) extra space besides the output list.
- The direction-vector alternative (turn right when blocked) and its O(m·n) visited grid.
- Python specifics: check
not matrix or not matrix[0]before readingmatrix[0],range(right, left - 1, -1)for walking backwards, negative indices silently read from the end instead of raising, and thematrix.pop(0)+zipone-liner destroys the input.
Clarifying questions expected:
- "Can the matrix be non-square or empty?"
- "May I modify the input?"
Code / implementation expected: Yes — a Python spiral_order(matrix) using four boundaries.