CodeSpeek

Spiral Matrix

Medium · Math & Geometry

You are given a 2D grid of integers with r rows and c columns. Return the elements of the grid as a single list ordered by walking the outer boundary clockwise starting at the top-left corner, then continuing inward layer by layer in the same clockwise spiral pattern until every cell has been visited exactly once.

Examples

Input:  matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Why:    Walking the outer ring clockwise then spiraling inward visits the center last.
Input:  matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Why:    The top row, right column, bottom row, and left column are traced in order, then the remaining inner row is read left to right.
Input:  matrix = [[7]]
Output: [7]
Why:    A single cell matrix has only one element to visit.

Constraints

1 <= matrix.length, matrix[0].length <= 10, -100 <= matrix[i][j] <= 100

Practise it by voice

Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.

Practise Spiral Matrix

This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Spiral Matrix. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.