v9.1.1
Menu

Spiral Matrix

mediumPROArrays & Matrix OperationsDSA for AI Engineers

Given an m x n matrix, return all elements in spiral order as a list.

The tests print the returned list space-separated.

Example

Input
1,2,3
4,5,6
7,8,9
Output
1 2 3 6 9 8 7 4 5
Reasoning
  • The input is a 3×33 \times 3 grid written row by row: 1,2,3 is the top row, 4,5,6 the middle row and 7,8,9 the bottom row. Spiral order walks the outer border clockwise from the top-left corner, then repeats on whatever is left inside.
  • Outer ring: the top edge, left to right, gives 1, 2, 3. The right edge going down adds 6, 9. The bottom edge, right to left, adds 8, 7. The left edge going up adds only 4, because 7 and 1 are corners already visited.
  • That ring covers 3+2+2+1=83 + 2 + 2 + 1 = 8 cells, each exactly once.
  • What remains is a 1×11 \times 1 inner grid holding 5, which comes last: 1 2 3 6 9 8 7 4 5.
  • Notice that for a non-square grid the inner remainder can be a single row: the 3×43 \times 4 test finishes its outer ring at 5 and then reads the leftover row 6, 7 left to right.

Constraints

  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

More from DSA for AI Engineers

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.