Search⌘ K
AI Features

Spiral Matrix

Understand how to convert an m by n matrix into a spiral order array. Learn step-by-step logic for traversing and transforming matrices in coding interviews.

Statement

Given an m×nm\times n matrix, return an array containing the matrix elements in spiral order, starting from the top-left cell.

Constraints:

  • 11\leq matrix.length 10\leq 10
  • 11\leq matrix[i].length 10\leq 10
  • 100-100\leq matrix[i][j] 100\leq 100

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Spiral Matrix

1.

What is the output if the following matrix is given as input?

matrix = [[2, 6, 8],
                  [3, 4, 8],
                  [9, 8, 8]]

A.

[2, 6, 8, 3, 4, 8, 9, 8, 8]

B.

[2, 6, 8, 8, 8, 8, 9, 3, 4]

C.

[2, 6, 8, 8, 4, 3, 9, 8, 8]

D.

[8, 6, 2, 3, 9, 8, 8, 8, 4]


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
1
2
3
4
5
6

Try it yourself

Implement your solution in the following coding playground:

Java
usercode > SpiralOrder.java
import java.util.*;
public class SpiralOrder {
public static List<Integer> spiralOrder(int[][] matrix) {
// Replace this placeholder return statement with your code
return new ArrayList<Integer>();
}
}
Spiral Matrix