DSA interview question
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].
vector<int> spiralOrder(const vector<vector<int>>& m); // m is non-empty, possibly non-square
Input m | Output | Explanation |
|---|---|---|
[[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.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in