PPractick

DSA interview question

Print a Matrix in Spiral Order

Medium · Algorithms · Topics: array, matrix, simulation

The problem

A printer for a museum's "spiral mosaic" exhibit reads tiles from a rectangular grid in spiral order: across the top row, down the right column, back along the bottom row, up the left column, then around again one layer further in. The logic sounds simple, but spiral traversal is a notorious source of off-by-one bugs, especially on non-square grids and single rows or columns. Four shrinking boundaries (top, bottom, left, right) keep it under control.

Example: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] → [1, 2, 3, 6, 9, 8, 7, 4, 5].

Function signature

vector<int> spiralOrder(const vector<vector<int>>& m);  // m is non-empty, possibly non-square

Test cases

Input mOutputExplanation
[[1,2,3],[4,5,6],[7,8,9]][1,2,3,6,9,8,7,4,5]
[[1,2,3,4],[5,6,7,8],[9,10,11,12]][1,2,3,4,8,12,11,10,9,5,6,7]3 × 4: the inner layer is a single row
[[1,2],[3,4]][1,2,4,3]
[[1,2,3]][1,2,3]A single row must not be read backwards again
[[1],[2],[3]][1,2,3]A single column must not be read upwards again
[[7]][7]

(Confirm: the matrix may be rectangular; every element appears exactly once in the output.)

How interviewers phrase it

Clarifying questions to ask

  1. Is the matrix square or rectangular?
  2. Clockwise, starting at the top-left?
  3. Can it be empty?

Follow-ups to expect

  1. "How do you avoid double-counting on a single row or column?"
  2. "How many layers are there?"
  3. "Is there another way?"
  4. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in