← Back to Codes

2026-06-09 16:36:42

Spiral Matrix in Python and Java | LeetCode #54

Learn how to solve Spiral Matrix in Python and Java with beginner-friendly explanation, step-by-step dry run, custom examples, and time complexity.

Spiral Matrix in Python and Java

In this tutorial, we will learn LeetCode #54: Spiral Matrix in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.

What Is the Spiral Matrix Problem?

This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.

For this problem, we will use boundary traversal because it gives a clean and optimized solution.

Example input:
matrix = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]

Expected result:
Output: [1,2,3,6,9,12,11,10,7,4,5,8]

Explanation:
Read the matrix in spiral order.

Beginner-Friendly Idea

The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.

At each step, ask: “What do I already know, and how does the current value change my answer?”

Using our example:
matrix = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]

Approach:
boundary traversal

We update variables step by step until we reach:
Output: [1,2,3,6,9,12,11,10,7,4,5,8]

Why Do We Use This Approach?

A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.

That is why boundary traversal is useful for this problem.

Step-by-Step Explanation

Let us dry run the algorithm using a custom example.

Step 1
Use this custom example.

matrix = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]

We will solve it using boundary traversal.

Step 2
Look at the first important value from the example and create the variables needed by the algorithm.

current_state = based on the first value
answer = not finished yet

Step 3
Move to the next useful value and update the state.

The algorithm compares the new value with the old state.
If the new value improves the answer, we update the answer.

Step 4
Continue this process until all useful values are processed.

After processing the example, we get:

Output: [1,2,3,6,9,12,11,10,7,4,5,8]

Why?
Read the matrix in spiral order.

Important Code Logic

The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.

Think like this:

old_state = what we knew before
current_value = value we are checking now
new_state = updated result after using current_value

For our example, the final state gives:
Output: [1,2,3,6,9,12,11,10,7,4,5,8]

Example 1

Input:
matrix = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]

Output:
Output: [1,2,3,6,9,12,11,10,7,4,5,8]

Explanation:
Read the matrix in spiral order.

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:
Read the matrix around the border, then move inside.

Python Code

Here is the complete Python solution for LeetCode #54.

class SpiralMatrixReader:
    def spiral_order(self, matrix):
        result = []
        top = 0
        bottom = len(matrix) - 1
        left = 0
        right = len(matrix[0]) - 1

        while top <= bottom and left <= right:
            for col in range(left, right + 1):
                result.append(matrix[top][col])
            top += 1

            for row in range(top, bottom + 1):
                result.append(matrix[row][right])
            right -= 1

            if top <= bottom:
                for col in range(right, left - 1, -1):
                    result.append(matrix[bottom][col])
                bottom -= 1

            if left <= right:
                for row in range(bottom, top - 1, -1):
                    result.append(matrix[row][left])
                left += 1

        return result


reader = SpiralMatrixReader()
print(reader.spiral_order([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))  # Output: [1,2,3,6,9,8,7,4,5]

Java Code

Here is the complete Java solution for LeetCode #54.

import java.util.ArrayList;
import java.util.List;

class SpiralMatrixReader {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        int top = 0;
        int bottom = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;

        while (top <= bottom && left <= right) {
            for (int col = left; col <= right; col++) result.add(matrix[top][col]);
            top++;

            for (int row = top; row <= bottom; row++) result.add(matrix[row][right]);
            right--;

            if (top <= bottom) {
                for (int col = right; col >= left; col--) result.add(matrix[bottom][col]);
                bottom--;
            }

            if (left <= right) {
                for (int row = bottom; row >= top; row--) result.add(matrix[row][left]);
                left++;
            }
        }

        return result;
    }

    public static void main(String[] args) {
        SpiralMatrixReader reader = new SpiralMatrixReader();
        System.out.println(reader.spiralOrder(new int[][] {{1,2,3}, {4,5,6}, {7,8,9}})); // [1, 2, 3, 6, 9, 8, 7, 4, 5]
    }
}

Time and Space Complexity

Time Complexity: O(n)

The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.

Space Complexity: O(n)

The extra space is used for the variables or data structures needed by the optimized approach.

Final Summary

LeetCode #54: Spiral Matrix becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.