LeetCode 54: Spiral Matrix – Java Solution Explained (Four-Pointer Technique)

LeetCode 54: Spiral Matrix

Struggling with the Spiral Matrix problem on LeetCode? You’re not alone! This guide breaks down an elegant and efficient solution using the four-pointer approach in Java. Whether you’re preparing for technical interviews or brushing up on matrix traversal techniques, this walkthrough has got you covered.


🔍 Problem Summary

Given an m x n matrix, return all its elements in spiral order. Think of starting at the top-left corner and moving in a spiral: right ➝ down ➝ left ➝ up, tightening the loop inward with each turn.

Example Input:

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

Output:

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

🚀 Optimal Strategy: Four-Pointer Approach

The best way to approach this is by using four boundaries to track the current layer you’re traversing:

  • startRow and endRow → Row boundaries
  • startCol and endCol → Column boundaries

The Spiral Pattern:

  1. Top Row → left to right
  2. Right Column → top to bottom
  3. Bottom Row → right to left (if any rows remain)
  4. Left Column → bottom to top (if any columns remain)

After each traversal, adjust the boundaries inward.


🔄 Step-by-Step Walkthrough

Let’s walk through the earlier example:

Initial Matrix:

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

First Layer Traversal:

  • Top: 1, 2, 3
  • Right: 6, 9
  • Bottom: 8, 7
  • Left: 4

Second Layer:

  • Remaining element: 5

💻 Java Implementation

import java.util.*;

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        int m = matrix.length, n = matrix[0].length;
        int startRow = 0, endRow = m - 1, startCol = 0, endCol = n - 1;

        while (startRow <= endRow && startCol <= endCol) {
            // Traverse top row
            for (int i = startCol; i <= endCol; i++) {
                result.add(matrix[startRow][i]);
            }
            startRow++;

            // Traverse right column
            for (int i = startRow; i <= endRow; i++) {
                result.add(matrix[i][endCol]);
            }
            endCol--;

            // Traverse bottom row
            if (startRow <= endRow) {
                for (int i = endCol; i >= startCol; i--) {
                    result.add(matrix[endRow][i]);
                }
                endRow--;
            }

            // Traverse left column
            if (startCol <= endCol) {
                for (int i = endRow; i >= startRow; i--) {
                    result.add(matrix[i][startCol]);
                }
                startCol++;
            }
        }
        return result;
    }
}

🧠 Why This Works

  • Time Complexity: O(m * n) – Each element is visited once.
  • Space Complexity: O(1) – Extra space used is constant (excluding the result list).

The key here is careful boundary control. The if checks prevent double-counting in edge cases like single rows or columns.


⚠️ Edge Cases to Watch For

  • Single row: Only top traversal
  • Single column: Only right traversal
  • Rectangular matrices: Properly adjust rows/columns based on matrix dimensions

Conclusion

The four-pointer method is a powerful pattern for problems involving layered traversal like this. It’s clean, intuitive, and interview-friendly.

Want to take it further? Check out related problems:


Keywords: spiral matrix Java, LeetCode 54, spiral order traversal, matrix algorithm, coding interview prep, four-pointer approach

Keep practicing, and you’ll have spiral matrices wrapped around your finger in no time. Happy coding! 💻✨


Let me know if you’d like a version tailored for Python or a visual diagram to go with the post!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *