Scrivio Interview library
CodingIntermediate6 min read · updated 12 November 2026

Write a Java method that returns the elements of an m x n matrix in spiral order (clockwise from the top left). Show how you avoid repeating elements when the matrix has a single row or column left.

We keep four bounds, top, bottom, left and right, and walk the matrix in rings: the top row from left to right, the right column downwards, the bottom row from right to left, and the left column upwards, shrinking the matching bound after each side. Before the bottom row and the left column passes we check top <= bottom and left <= right, because when a single row or column is left, the earlier passes have already visited it and it would otherwise be printed twice. The walk is O(m n) time and O(1) extra space besides the output list, and we return an empty list for an empty matrix.

Why this question is asked

Spiral traversal is a pure boundary-handling problem. There is no clever algorithm to discover; the whole question is whether we can keep four indexes correct and handle the moment when the remaining area collapses into a single row or column. That is the same skill we need in real code that walks image tiles, paginates a grid, or processes a ring buffer, and it is why interviewers ask it. In this answer, we will recap the traversal with four bounds, write the method, reproduce the duplicate-element bug on a single row, fix it with the two checks, handle empty input, and finish with filling a matrix in spiral order.

1A Quick Recap of Spiral Order

Spiral order starts at the top left and goes clockwise around the outside of the matrix, then around the next ring inside, until every element has been visited once. For the 3 x 4 matrix with rows [1, 2, 3, 4], [5, 6, 7, 8] and [9, 10, 11, 12], the order is 1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7.

Instead of keeping a visited array, we describe the part of the matrix we have not visited yet with four bounds: top is the first unvisited row, bottom the last, left the first unvisited column and right the last. After walking a side, we move the corresponding bound one step inwards. The loop continues while there is still a non-empty rectangle, that is while top <= bottom and left <= right.

2Walking the Four Sides

Each ring is four passes. After each pass, one bound shrinks, which removes the side we just walked from the unvisited rectangle.

Java
static List<Integer> spiralOrder(int[][] matrix) {
List<Integer> out = new ArrayList<>();
if (matrix.length == 0 || matrix[0].length == 0) return out; // empty input
int top = 0, bottom = matrix.length - 1;
int left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (int c = left; c <= right; c++) out.add(matrix[top][c]); // top row ->
top++;
for (int r = top; r <= bottom; r++) out.add(matrix[r][right]); // right column down
right--;
if (top <= bottom) { // a row is still left
for (int c = right; c >= left; c--) out.add(matrix[bottom][c]); // bottom row <-
bottom--;
}
if (left <= right) { // a column is still left
for (int r = bottom; r >= top; r--) out.add(matrix[r][left]); // left column up
left++;
}
}
return out;
}
spiralOrder(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]
Step throughOne ring of the spiral
  1. Top row, left to rightthen top++
  2. Right column, top to bottomthen right--
  3. top <= bottom?
    YesBottom row, right to left, then bottom--NoSkip: that row was the top row
  4. left <= right?
    YesLeft column, bottom to top, then left++NoSkip: that column was the right column
  5. Rectangle still non-empty?
    YesNext ringNoDone

5 steps in order. Play them, or step through them one at a time.

Notice that the first two passes need no check. The loop condition guarantees the rectangle is non-empty when we start the top row, and if moving top inwards makes the rectangle empty, the right column loop simply runs zero times, because its condition r <= bottom fails immediately.

3The Duplicate Bug on a Single Row or Column

Without the two checks, the code works on square matrices and on many rectangles, which is why the bug survives quick tests. A single row shows it.

Java
// Without the checks, matrix = {{1, 2, 3}}
// top row: 1, 2, 3 top = 1, bottom = 0
// right column: (r from 1 to 0: nothing) right = 1
// bottom row: row 0 from column 1 to 0: 2, 1 (already visited!)
// left column: (r from -1 to 1: nothing)
// result: [1, 2, 3, 2, 1] expected [1, 2, 3]
// The same happens with a single column {{1}, {2}, {3}}:
// without the left <= right check the result is [1, 2, 3, 2]

The reason is that once top passes bottom, there is no row left, but the bottom row loop does not know that: it only checks the columns, which are still in range. It walks row bottom, which is the same row the top pass just visited. Symmetrically, after right passes left, the left column loop walks the column the right pass already visited. The checks top <= bottom and left <= right ask, right before each of those passes, whether the rectangle still has a row or a column for it to visit.

With the checks, the single row produces [1, 2, 3] and the single column produces [1, 2, 3]. A good habit is to test exactly these shapes, plus 1 x 1, 2 x 2, and a tall and a wide rectangle, because they are where the rectangle collapses.

4Complexity and Empty Input

Every element is added to the output exactly once, and each loop step adds one element, so the time is O(m n). Besides the output list, we keep four ints, so the extra space is O(1). The output itself is O(m n), which is required by the question.

Empty input needs its own check, because matrix[0] would throw ArrayIndexOutOfBoundsException when there are no rows. We return an empty list for both new int[0][0] and a matrix whose rows are empty. If the input could be jagged, with rows of different lengths, spiral order is not well defined, and I would validate the shape and throw IllegalArgumentException.

5Follow-up questions

How would you fill a matrix in spiral order with 1 to n^2?

I use exactly the same four bounds and the same four passes, but instead of reading matrix[r][c] into a list I write a counter into it: matrix[top][c] = value++ and so on. For a square n x n matrix the rectangle collapses symmetrically, but keeping the two checks costs nothing and makes the code correct for rectangles too. The result for n = 3 is rows [1, 2, 3], [8, 9, 4], [7, 6, 5].

Could you use a direction array instead of four loops?

Yes. I keep the direction vectors right, down, left and up, a visited array, and turn clockwise whenever the next cell is outside the matrix or already visited. It is shorter and handles collapse automatically, but it needs O(m n) extra space for visited, unless we mark cells in the input, which destroys it. The four-bound version needs no extra space, which is why I prefer it.

How would you print it counterclockwise?

I change the order of the passes: left column downwards, bottom row left to right, right column upwards, top row right to left, with the same kind of check before the third and fourth passes.

6Conclusion

In this answer, we walked a matrix in spiral order with four bounds that describe the unvisited rectangle, shrinking one bound after each of the four passes. We saw why a single remaining row or column is visited twice without the checks top <= bottom and left <= right before the bottom row and left column passes, reproduced it on a 1 x 3 matrix, and fixed it. The method is O(m n) time with O(1) extra space, returns an empty list for empty input, and the same structure fills a matrix with 1 to n^2.

What to say in the interviewAbout 100 seconds aloud

Open with

I would keep four bounds for the part of the matrix I have not visited yet: top, bottom, left and right. While top is at most bottom and left is at most right, I walk one ring.

Then, if they want more

I go along the top row from left to right and move top down. Then I go down the right column and move right inwards. Then, only if top is still at most bottom, I go along the bottom row from right to left and move bottom up.

Then, only if left is still at most right, I go up the left column and move left inwards. Those two checks are the important detail.

When only one row is left, the top pass already visited it, and without the check the bottom pass would walk the same row backwards, so a single row 1 2 3 would come out as 1 2 3 2 1. The same happens with a single remaining column and the left pass.

The first two passes do not need checks because their loops simply run zero times when the rectangle is empty. Every element is added once, so it is O(m n) time, and apart from the output list I use four ints, so O(1) extra space.

I would also return an empty list for an empty matrix before touching matrix zero, and I would test 1 by 1, a single row, a single column, and a tall and a wide rectangle, because those are where the spiral collapses.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
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 "Write a Java method that returns the elements of an m x n matrix in spiral order...": https://scrivio-interview-library.netlify.app/java/coding-problems/9e9244cc7d/