← All Exercises

Spiral Matrix Traversal

basictypescript~25min

Background

Spiral traversal appears in image rotation, matrix reshaping, and interview warm-ups about boundary bookkeeping.

Problem

Given a non-empty rectangular matrix, return all its elements in clockwise spiral order starting from the top-left corner.

Input

A non-empty two-dimensional array of numbers with consistent row lengths.

Output

A flat array containing every element exactly once in spiral order.

Sample tests

Sample 1

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

Sample 2

Input: matrix = [[1,2,3,4]]
Expected: [1,2,3,4]

Sample 3

Input: matrix = [[1],[2],[3]]
Expected: [1,2,3]

Your solution

Learning objective

Coordinate four boundary pointers and guard degenerate rows and columns in matrix traversal.