Back to problems Sign in to unlock
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
gfgProblem Statement
Problem
You are given an matrix of integers. Start at the top-left cell and visit every element exactly once in clockwise spiral order:
- Move left to right across the top row.
- Move top to bottom down the rightmost remaining column.
- Move right to left across the bottom row, if any remain.
- Move bottom to top up the leftmost remaining column, if any remain.
- 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
matrixwithmrows andncolumns.
Output Format
- A list of integers representing the matrix values in clockwise spiral order.
Constraints
- 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
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.