ExamAdda Logo

Spiral Matrix

Easy

Given an m × n matrix, return all elements of the matrix in spiral order.

The spiral traversal starts from the top-left corner and moves:

Right → Down → Left → Up

 

and continues inward until every element has been visited.

Example

Input:

1  2  3

4  5  6

7  8  9

 

Spiral traversal:

1 → 2 → 3 → 6 → 9 → 8 → 7 → 4 → 5

 

Output

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

 

Main Idea

Maintain four boundaries:

top

bottom

left

right

 

Initially:

top = 0

bottom = rows - 1

left = 0

right = columns - 1

 

Process the matrix in four directions.

1. Move Right

Traverse from:

left → right

 

along the top row.

Then:

top++

 

2. Move Down

Traverse from:

top → bottom

 

along the right column.

Then:

right--

 

3. Move Left

Traverse from:

right → left

 

along the bottom row.

Then:

bottom--

 

4. Move Up

Traverse from:

bottom → top

 

along the left column.

Then:

left++

 

Continue while:

top <= bottom && left <= right

 

Example

1  2  3

4  5  6

7  8  9

 

First outer layer:

1 2 3

    6

    9

7 8

4

 

Then only 5 remains.

Final order:

1 2 3 6 9 8 7 4 5

 

Example 1

Input

3 3
1 2 3
4 5 6
7 8 9

Output

1 2 3 6 9 8 7 4 5

Constraints

1 <= m
n <= 10
-100 <= matrix[i][j] <= 100

Hints:

Hint 1

Think of the matrix as having four moving boundaries.

Hint 2

Traverse one complete outer layer at a time.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 17, 2026

Last updated

Aug 18, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output