Skip to question
asic.fyi
DesignVerificationSystemVerilogFirmwareArchitectureInterviews
asic.fyi/Interview questions/Traverse a matrix in spiral order

Hardware interview practice

Traverse a matrix in spiral order

MediumMatricesSystemVerilog

Return the elements of a rectangular matrix in clockwise spiral order.

Try it in the question bankReason first. Then compare.

Keep this exact question selected while you check your answer and review the full solution.

Practice this question →
Reviewed example

Work through one case

Input
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Expected output
[1, 2, 3, 6, 9, 8, 7, 4, 5]

Each perimeter is emitted clockwise before the bounds contract to the next inner layer.

What to cover

Requirements

  1. Support rectangular and single-row or single-column inputs.
  2. Assume every input row has the same number of columns.
  3. Guard the bottom and left traversals after shrinking the boundaries.
  4. Return an empty queue for an empty input.
asic.fyi · Learn silicon end to end.info@asic.fyi