Given an m x n matrix, return all elements in spiral order (clockwise from the outside inward).
For example:
Input: Output: 1 2 3 [1, 2, 3, 6, 9, 8, 7, 4, 5] 4 5 6 7 8 9
Another example:
1 2 3 4 [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] 5 6 7 8 9 10 11 12
Explain your approach, how you handle non-square matrices, and analyze the time and space complexity.
How to approach it
- Hint 1
Think of the matrix as having four boundaries: top row, bottom row, left column, right column. Traverse one boundary at a time.
- Hint 2
After traversing a boundary, shrink it inward (e.g., after traversing the top row, increment the top boundary).
- Hint 3
Be careful with the termination condition -- when do you stop? What happens when the boundaries cross?
Ready to answer it out loud?
Record your answer in 1:30 and Preptile scores it 1–10 with specifics — what landed, what you skipped, and what to say next time.
Practising needs an invite code. Join the waitlist and we’ll send you one.