Spiral Matrix is a classic interview problem tagged with Array, Matrix, and Simulation, commonly asked by Microsoft. It requires traversing a 2D matrix in a clockwise spiral starting from the top-left corner.[1][10]
Given an m x n matrix, return all elements of the matrix in spiral order. The spiral starts at the top-left corner and moves right, then down, then left, then up, continuing inward layer by layer until all elements are covered.[10][1]
For a standard 4x4 matrix:
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] Output: [1,2,3,4,8,12,16,15,14,13,9,5,6,10,11,7]
This traces: right → down → left → up → right → down → left → up.[7][1]
Single row example:
Input: matrix = [[1,2,3,4]] Output: [1,2,3,4]
Single column example:
Input: matrix = [[1],[2],[3],[4]] Output: [1,2,3,4]
Empty matrix:
Input: matrix = [] Output: []
Irregular shape (2x3):
Input: matrix = [[1,2,3],[4,5,6]] Output: [1,2,3,6,5,4]