Scrivio Interview library
Matrices and simulationMatrices and gridsReported 33 times · 15 min read · updated 15 November 2026

Print the elements of a matrix in spiral order.

1What it means to read a matrix in spiral order

Think of mowing a rectangular lawn from the outside in. You push the mower along the top edge, turn right at the corner and go down the right edge, turn again along the bottom, and come back up the left side. After one lap, the part still to mow is a smaller rectangle inside, and you do the same lap around it, until nothing is left. Reading a matrix in spiral order is exactly that lap, done with numbers instead of grass.

A matrix is a grid of numbers stored as rows, and in Java it is an array of arrays, so m[r][c] is the number in row r and column c, both counted from 0. We must return all the numbers in spiral order: start at the top-left corner, go right along the top row, down the right column, left along the bottom row, up the left column, then repeat one layer further in, until every number has been listed once.

Let us keep one example, the 3 by 4 matrix with rows 1 2 3 4, then 5 6 7 8, then 9 10 11 12. Do it by hand with me. Along the top: 1, 2, 3, 4. Down the right column, not repeating the 4: 8, 12. Back along the bottom, not repeating the 12: 11, 10, 9. Up the left column, not repeating the 9 and stopping before the 1: 5. That is the outer ring. What is left is the middle row, 6 and 7, which we read left to right. The answer is 1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7.

PictureThe 3 by 4 example matrix and its spiral

The outer ring is listed first, clockwise from the top-left corner; the two marked cells in the middle are the inner layer.

  1. 123456789101112
    outer ring
    1 2 3 4 8 12 11 10 9 5
    inner layer
    6 7
    expected
    1 2 3 4 8 12 11 10 9 5 6 7

    1The spiral starts at 1, goes right to 4, down to 12, left to 9 and up to 5, then finishes with the inner layer, 6 and 7.

What to assume

Is the matrix square?
Not necessarily; it may be rectangular, a single row or a single column.
Can it be empty?
Yes, and then we return an empty list.
Do we go clockwise from the top-left?
Yes.
Should we return the numbers in a list?
Yes, a List of Integer.

Notice the little care we took at every corner: each corner number belongs to exactly one side, so no number is listed twice. Notice too that the inner layer was not a ring at all, just a single row. Those two observations are where every bug in this problem lives, and the rest is easy.

A careful candidate asks about the shape first. Is the matrix square? Not necessarily; it may be rectangular, a single row or a single column. Can it be empty? Yes, and then we return an empty list. Do we go clockwise from the top-left? Yes. Should we return the numbers in a list? Yes, a List of Integer.

2How to spot the simulation pattern

When beginners first meet this question, many of them hunt for a formula that says which number comes in position k of the spiral. That is a natural thing to look for, because so many problems hide a clever trick. Here there is no trick to find, and it is a relief to see why. Let us read the question slowly and take its clues one at a time.

The first clue is that the question describes a path. It tells us exactly where to go: right, then down, then left, then up, then inward. When a problem spells out the movement step by step, the job is not to discover anything but to follow the description carefully, which programmers call simulation.

The second clue is the word matrix together with that movement. In a grid, moving means changing a row index or a column index by one. So our program will be a few loops, each walking one row or one column, and the only real question is how to know where each loop starts and stops.

Together these clues point to the matrices and simulation family. Simulation means doing exactly what the question describes, one step at a time, while keeping a small amount of state that tells us where we are. For the spiral, that state is the edges of the rectangle not yet listed, the lawn not yet mown. The general rule to carry to new problems is to describe the unfinished part of the grid with as few numbers as possible and update those numbers after each move.

Some patterns look similar but do not fit. Breadth first and depth first search also walk through grids, but they spread out to every neighbour they can reach, not along a fixed route, so they cannot produce a spiral. Recursion on layers is possible, but it is the same simulation written differently.

3The honest first attempt, a brute force walker with a visited grid

The first solution that works imitates a person walking the lawn without a plan. Keep a direction, starting with right. List the current cell, mark it as visited, and try to take one step forward. If that step would leave the matrix or land on a visited cell, turn clockwise and step in the new direction instead. A second grid of booleans, the same size as the matrix, remembers which cells are visited. This brute force is correct, and it is a fine first answer.

Java
static List<Integer> spiralVisited(int[][] m) {
List<Integer> out = new ArrayList<>();
if (m.length == 0) return out;
int rows = m.length, cols = m[0].length;
boolean[][] seen = new boolean[rows][cols]; // a second grid, as large as the input
int[] dr = {0, 1, 0, -1}, dc = {1, 0, -1, 0}; // right, down, left, up
int r = 0, c = 0, d = 0;
for (int k = 0; k < rows * cols; k++) {
out.add(m[r][c]);
seen[r][c] = true;
int nr = r + dr[d], nc = c + dc[d];
if (nr < 0 || nr >= rows || nc < 0 || nc >= cols || seen[nr][nc]) {
d = (d + 1) % 4; // blocked: turn clockwise
nr = r + dr[d];
nc = c + dc[d];
}
r = nr;
c = nc;
}
return out;
}

Let us follow it on the example for a few steps. From 1 we step right to 2, 3 and 4. The next step right would leave the matrix, so we turn and go down to 8 and 12. Below 12 is outside, so we turn left: 11, 10, 9. Left of 9 is outside, so we turn up to 5. Above 5 is the 1, already visited, so we turn right to 6 and 7. That is twelve cells, each listed once, so the time is O(m * n), read as order m times n, for m rows and n columns.

So where is the waste? It is the second grid. To produce twelve numbers we allocated twelve booleans, and for a 1,000 by 1,000 matrix we would allocate a million, as large as the input. Every single step also pays for a bounds check and a look-up in that grid. The extra space is O(m * n).

Look at what the grid records, though. After every complete stroke, the unvisited cells always form a rectangle, because each stroke removes one whole outer row or column of it. A rectangle can be described by four numbers, its first and last row and its first and last column. So the question that leads further is whether four numbers can replace the whole visited grid.

4Getting to four boundaries, one observation at a time

Let us name the four numbers. top is the first row not yet listed and bottom is the last; left is the first column not yet listed and right is the last. For the example they start at 0, 2, 0 and 3. As long as top <= bottom and left <= right, the rectangle between them still holds at least one cell, so the main loop runs while both are true.

Each lap is four strokes, and after each stroke one boundary moves inward. First we walk row top from left to right, and since that row is now finished, top goes up by one. Then we walk column right from top to bottom, and right goes down by one. Then row bottom from right to left, and bottom goes down by one. Finally column left from bottom up to top, and left goes up by one. Because each stroke starts after the previous boundary moved, no corner is listed twice, which is the care we took by hand.

Step throughWhat goes wrong on a single row without the guard

The matrix {{1, 2, 3}} run through the four strokes with no checks. The third stroke walks the same row backwards.

  1. 123
    top
    1
    bottom
    0
    left
    0
    right
    2
    output
    1 2 3

    1The top stroke lists 1, 2 and 3 and moves top down to 1. top is now below bottom, which is 0, so no rows are left.

  2. 123
    top
    1
    bottom
    0
    left
    0
    right
    1
    output
    1 2 3

    2The right stroke runs r from top 1 to bottom 0, which lists nothing, and right moves in to 1.

  3. 123
    top
    1
    bottom
    -1
    left
    0
    right
    1
    output
    1 2 3 2 1 (wrong)

    3With no guard, the bottom stroke walks row bottom, which is row 0 again, from right 1 to left 0, and lists 2 and 1 a second time.

Here is the question a beginner asks. Why do we need any checks inside the loop, when the while condition already checks the rectangle? Let us try the single row matrix {{1, 2, 3}} without checks and see what goes wrong. The top stroke lists 1, 2, 3 and moves top to 1, which is already below bottom 0. The right stroke lists nothing. But the bottom stroke still walks row bottom, which is row 0 again, from right to left, and lists 2 and 1 a second time. The while condition is only tested at the start of a lap, and the rectangle can collapse in the middle of one.

So we add two guards. Before the bottom stroke we check top <= bottom, which says a row is still left; before the left stroke we check left <= right, which says a column is still left. These are the two lines beginners most often forget, and they are tempting to leave out because square matrices happen to work without them.

Why is the method correct? At the start of every lap the unlisted cells form exactly the rectangle from top to bottom and left to right. Each stroke lists one edge of that rectangle and moves the matching boundary past it, so the rectangle stays exact. The guards make sure a stroke only runs on an edge that still exists, so no cell is listed twice, and the loop ends only when the rectangle is empty, so no cell is missed.

5Watching the boundaries close in on the 3 by 4 example

The picture plays the method on our 3 by 4 matrix, one frame per stroke. The cells a stroke lists are marked as being looked at, and cells listed earlier are marked as done. The panel shows the four boundaries after the stroke and the output so far.

Watch the second lap closely, because the inner layer is a single row and the guards come into play there.

Step throughSpiral order on the 3 by 4 matrix, stroke by stroke

Cells being listed by the current stroke are highlighted; finished cells are marked done. The panel shows the boundaries after each stroke.

  1. 123456789101112
    top
    0
    bottom
    2
    left
    0
    right
    3
    output
    empty

    1Nothing is listed yet. The unlisted part is the whole matrix, rows 0 to 2 and columns 0 to 3, so top is 0, bottom 2, left 0 and right 3.

  2. 123456789101112
    top
    1
    bottom
    2
    left
    0
    right
    3
    output
    1 2 3 4

    2The top stroke walks row 0 from left to right, listing 1, 2, 3 and 4. Row 0 is finished, so top moves down to 1.

  3. 123456789101112
    top
    1
    bottom
    2
    left
    0
    right
    2
    output
    1 2 3 4 8 12

    3The right stroke walks column 3 from top 1 to bottom 2, listing 8 and 12. Column 3 is finished, so right moves in to 2.

  4. 123456789101112
    top
    1
    bottom
    1
    left
    0
    right
    2
    output
    1 2 3 4 8 12 11 10 9

    4top 1 is still at most bottom 2, so a bottom row remains. We walk row 2 from right 2 to left 0, listing 11, 10 and 9, and bottom moves up to 1.

  5. 123456789101112
    top
    1
    bottom
    1
    left
    1
    right
    2
    output
    1 2 3 4 8 12 11 10 9 5

    5left 0 is at most right 2, so a left column remains. We walk column 0 from bottom 1 up to top 1, listing only 5, and left moves in to 1.

  6. 123456789101112
    top
    2
    bottom
    1
    left
    1
    right
    2
    output
    1 2 3 4 8 12 11 10 9 5 6 7

    6The outer ring is done and the unlisted part is row 1, columns 1 to 2. The top stroke lists 6 and 7 and moves top down to 2.

  7. 123456789101112
    top
    2
    bottom
    1
    left
    1
    right
    1
    output
    1 2 3 4 8 12 11 10 9 5 6 7

    7The right stroke would run from row 2 to row 1, an empty range, so it lists nothing. right moves in to 1.

  8. 123456789101112
    top
    2
    bottom
    1
    left
    1
    right
    1
    output
    1 2 3 4 8 12 11 10 9 5 6 7

    8Now top 2 is below bottom 1, so the guard top <= bottom fails and the bottom stroke is skipped. Without this check we would list 7 and 6 again.

  9. 123456789101112
    top
    2
    bottom
    1
    left
    2
    right
    1
    output
    1 2 3 4 8 12 11 10 9 5 6 7

    9left 1 is at most right 1, so the left stroke runs, but its range, from row 1 up to row 2, is empty. It lists nothing and left moves to 2.

  10. 123456789101112
    top
    2
    bottom
    1
    left
    2
    right
    1
    output
    1 2 3 4 8 12 11 10 9 5 6 7

    10top is now below bottom, so the while loop stops. Each of the twelve cells was listed exactly once, in spiral order.

Let us read the important frames back. The first lap, frames two to five, lists the outer ring, and after it the boundaries are top 1, bottom 1, left 1 and right 2, which describe exactly the cells 6 and 7. The left stroke in frame five lists only the 5, because it runs from bottom 1 up to top 1, a single row.

In the second lap the top stroke lists 6 and 7 and moves top to 2, below bottom. The right stroke's range is empty. In frame eight the guard top <= bottom fails, so the bottom stroke is skipped; without it, 7 and 6 would be listed again, as the single row picture showed. In frame nine the left guard passes, because left 1 is still at most right 1, but the stroke's own range is empty, so nothing is listed. Then the while loop stops with all twelve numbers in order.

6The complete Java program

Here is the full program. The spiral method follows the four strokes in order, with the two guards written as if statements around the third and fourth. main runs a 3 by 3 matrix, our 3 by 4 example, a single column, a single row and an empty matrix, and the comment on each line shows what it prints.

Java
import java.util.*;
public class SpiralMatrix {
// Peel the matrix layer by layer, shrinking four boundaries after each side.
static List<Integer> spiral(int[][] m) {
List<Integer> out = new ArrayList<>();
if (m.length == 0) return out;
int top = 0, bottom = m.length - 1, left = 0, right = m[0].length - 1;
while (top <= bottom && left <= right) {
for (int c = left; c <= right; c++) out.add(m[top][c]); // left to right along the top
top++;
for (int r = top; r <= bottom; r++) out.add(m[r][right]); // down the right side
right--;
if (top <= bottom) { // a bottom row is still left
for (int c = right; c >= left; c--) out.add(m[bottom][c]);
bottom--;
}
if (left <= right) { // a left column is still left
for (int r = bottom; r >= top; r--) out.add(m[r][left]);
left++;
}
}
return out;
}
public static void main(String[] args) {
System.out.println(spiral(new int[][] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}})); // [1, 2, 3, 6, 9, 8, 7, 4, 5]
System.out.println(spiral(new int[][] {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}})); // [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
System.out.println(spiral(new int[][] {{1}, {2}, {3}})); // [1, 2, 3]
System.out.println(spiral(new int[][] {{1, 2, 3}})); // [1, 2, 3]
System.out.println(spiral(new int[0][0])); // []
}
}

Let us read spiral in the order it runs. We create the output list and return it at once if the matrix has no rows, because m[0] would not exist. Then we set top to 0, bottom to the last row, left to 0 and right to the last column, so the rectangle covers everything.

Inside the while loop, the first for loop walks columns left to right along row top and adds each number; top++ then marks that row finished. The second for loop walks rows top to bottom down column right; right-- marks that column finished. The if around the third loop checks that a row remains before walking row bottom from right to left, then bottom--. The if around the fourth loop checks that a column remains before walking column left from bottom up to top, then left++.

The single column test, {{1}, {2}, {3}}, shows the second guard at work. The top stroke lists 1, the right stroke lists 2 and 3 and moves right to -1, so the guard left <= right fails and the upward stroke does not list 2 again. The single row test, {{1, 2, 3}}, shows the first guard, as in our picture. Both print [1, 2, 3].

7How much it costs, and the cases at the edges

Let us count on the example first. The twelve numbers were each added to the output exactly once, by seven strokes, two of which listed nothing. For m rows and n columns every cell is added once and each stroke costs one step per cell it lists, so the time is O(m * n). We cannot do better, because the answer itself has m * n numbers.

Apart from the output list, we keep four integers, whatever the size of the matrix, so the extra space is O(1), read as constant. That is the advantage over the visited grid, which needed O(m * n).

Comparing the two ways to walk the spiral
ApproachTimeExtra spaceWhere bugs hide
Walker with a visited gridO(m * n)O(m * n)turning rules and bounds checks
Four boundaries and two guardsO(m * n)O(1)the guards before strokes 3 and 4

The edge cases are all handled by the loop condition and the guards. An empty matrix returns an empty list before m[0] is read. A single cell is listed by the top stroke, after which the right stroke finds nothing and both guards fail. A single row and a single column each rely on one guard, as we saw. Rectangles whose innermost layer is a row or a column, such as our 3 by 4 example, finish correctly for the same reason.

8Follow-up questions

How would you fill an n by n matrix with the numbers 1 to n squared in spiral order?

We use exactly the same boundaries and strokes, but instead of reading m[r][c] into a list, we write a counter into m[r][c] and add one to the counter after each write. For a 3 by 3 matrix the counter runs from 1 to 9 around the ring and ends with 9 in the centre. The guards matter here too, because when n is odd the centre is a single cell that must be written once.

Could recursion peel the layers instead of a while loop?

Yes. A method can list the outer layer of the rectangle between four boundaries and then call itself with each boundary moved one step inward, stopping when the rectangle is empty. It is the same algorithm with the loop replaced by calls, and the depth of those calls is about half the smaller side of the matrix, which is small, so it is safe. The loop is usually preferred because it is easier to step through.

What changes for an anticlockwise spiral?

Only the order of the strokes. Starting at the top-left and going anticlockwise means going down the left column first, then right along the bottom row, then up the right column, then left along the top row, moving the matching boundary after each. The two guards move with the strokes: whichever two strokes come third and fourth need the check that their row or column still exists.

9Conclusion

We read a matrix in spiral order by keeping the unlisted part as a rectangle described by four boundaries. Each lap lists the top row, the right column, the bottom row and the left column, moving the matching boundary inward after each stroke, and two guards stop a single remaining row or column from being listed twice. It takes O(m * n) time and O(1) extra space. The clue to remember is a question that describes a path through a grid: simulate it, and describe the unfinished part with as few numbers as possible.

What to say in the interviewAbout 90 seconds aloud

Open with

Let me confirm the shape first. The matrix may be rectangular, a single row or column, or empty, and I list the numbers clockwise from the top-left corner.

Then, if they want more

A walker that turns when it hits an edge or a visited cell works, but it needs a visited grid as large as the input. I notice that after every stroke the unvisited cells form a rectangle, so four integers describe them: top, bottom, left and right.

While top is at most bottom and left is at most right, I list the top row from left to right and move top down, then the right column from top to bottom and move right in.

Then, only if top is still at most bottom, I list the bottom row from right to left and move bottom up, and only if left is still at most right, I list the left column from bottom to top and move left in.

Those two checks matter because the rectangle can collapse in the middle of a lap, and without them a single remaining row or column is listed twice. For the 3 by 4 example this gives 1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7.

Every element is listed once, so it is O(m * n) time and O(1) extra space besides the output.

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 33 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Print the elements of a matrix in spiral order.": https://scrivio-interview-library.netlify.app/data-structures/solutions/print-the-elements-of-a-matrix-in-spiral-order-4805a5/