Dsa
Matrix
Medium
Matrix Spiral Order
Given a 2D matrix, return its elements in spiral order. Start from the top-left corner, traverse the outer layer in a clockwise fashion, and continue inward until all elements are traversed.
Input format:
- The first line contains two integers, 'n' and 'm' (number of rows and columns).
- The next 'n' lines contain 'm' space-separated integers.
Output format:
- Print the elements in spiral order as a single line of space-separated integers.
Example:
Input:
3 4
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
Key concepts
matrixspiraltraversal
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now