Skip to the solution
MediumDSA6 min read

How do you traverse a matrix in spiral order?

468 views

The problem

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 while top <= 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 reading matrix[0], range(right, left - 1, -1) for walking backwards, negative indices silently read from the end instead of raising, and the matrix.pop(0) + zip one-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.

  • matrix
  • simulation

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 10 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonBoundary method on square, wide, tall, single-row, single-column and empty matrices
PythonDirection-vector simulation checked on all 36 shapes, plus generating a spiral matrix
PythonThe classic bug: missing the two inner guards, buggy vs fixed

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 90 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you compute the product of an array except self without division?

Continue