All practice tasks

Coding (Algo)

Read a Matrix in Spiral Order

Boundary traversal · Medium

A visualization tool reveals a rectangular matrix one outer ring at a time. It begins at the top-left corner and travels clockwise. Every cell must appear exactly once, including thin final rows or columns.

Return a flat array of all matrix values in clockwise spiral order without modifying the matrix.

Input

Call

  • Implement solve(input) and return the result. The provided adapter handles JSON input and output.

Input shape

A JSON object { "matrix": number[][] }.

Fields

  • matrix is rectangular. Every row has the same length, including when the length is zero.

Output

Return value

  • Start along the top row to the right, then down, left and up around each remaining ring.
  • Return every cell once. An empty dimension returns [].

Constraints

  • 0 <= rows, columns <= 1000; rows*columns <= 1000000.
  • Values are integers in [-1000000000,1000000000].

Examples

Example 1

{
  "matrix": [
    [
      1,
      2,
      3
    ],
    [
      4,
      5,
      6
    ]
  ]
}

Returns

[
  1,
  2,
  3,
  6,
  5,
  4
]

One rectangular ring.

Example 2

{
  "matrix": [
    [
      1
    ],
    [
      2
    ],
    [
      3
    ]
  ]
}

Returns

[
  1,
  2,
  3
]

Do not traverse the same column twice.

Required complexity

O(rows * columns) time and O(1) working space excluding output

What this task practices

Read a Matrix in Spiral Order is a coding (algo) interview exercise that trains prompt interpretation, explicit assumptions, a concrete response, and a clear explanation of tradeoffs. The catalog marks it as medium difficulty. It focuses on Technical Reasoning, Testing, Validation. The signed-in workspace provides the tools for the round and evaluates the attempt against task-specific criteria. Reference solutions, hidden checks, evaluator instructions, and candidate work remain private.

Sign in to startThe workspace and evaluation open after sign in.