Skip to main content
Back to problems
Leetcode
Medium
Arrays
Matrices
Simulation
Amazon
Spiral Matrix

Return all elements of a matrix in clockwise spiral order.

Acceptance 67%
Also Available On
Other platform versions and source mappings for the same problem.

Spiral Order

gfg
Problem Statement

Problem

You are given an m×nm \times n matrix of integers. Start at the top-left cell and visit every element exactly once in clockwise spiral order:

  1. Move left to right across the top row.
  2. Move top to bottom down the rightmost remaining column.
  3. Move right to left across the bottom row, if any remain.
  4. Move bottom to top up the leftmost remaining column, if any remain.
  5. Continue shrinking the unvisited boundary until all elements are collected.

Return the elements in the order they are visited.

Notes

  • The matrix may be rectangular, not necessarily square.
  • You must include every element exactly once.

Input Format

  • A 2D integer matrix matrix with m rows and n columns.

Output Format

  • A list of integers representing the matrix values in clockwise spiral order.

Constraints

  • 1m,n1 \le m, n
  • The matrix contains at least one element.
  • Each element should appear exactly once in the output.
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

[1,2,3,6,9,8,7,4,5]

Explanation

Traverse the outer layer first, then the remaining center element.

Example 2

Input

matrix = [[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]

Explanation

The traversal proceeds around the perimeter, then continues inward on the remaining submatrix.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.