54. Spiral Matrix 🌐

Difficulty: Medium - Tags: Matrix, Simulation

LeetCode Problem Link


Problem Statement 📜

Given an m x n matrix, return all elements of the matrix in spiral order.


Examples 🌟

🔹 Example 1:

Input:

Output:

🔹 Example 2:

Input:

Output:


Constraints ⚙️

  • m == matrix.length

  • n == matrix[i].length

  • 1 <= m, n <= 10

  • -100 <= matrix[i][j] <= 100


Solution 💡

To traverse the matrix in spiral order, we use boundary pointers for rows and columns and move in the order: left-to-right, top-to-bottom, right-to-left, and bottom-to-top.


Java Solution


Explanation of the Solution

  1. Initialization:

    • Define four boundary variables: top, bottom, left, and right.

  2. Traversal:

    • Left to Right: Traverse the current top row and increment top.

    • Top to Bottom: Traverse the current right column and decrement right.

    • Right to Left: Traverse the current bottom row (if valid) and decrement bottom.

    • Bottom to Top: Traverse the current left column (if valid) and increment left.

  3. Result:

    • Stop traversal when top > bottom or left > right.


Time Complexity ⏳

  • O(m * n):

    • Each element of the matrix is visited exactly once.

Space Complexity 💾

  • O(1):

    • No additional space is used apart from the result list (output space not counted).

You can find the full solution here.

Last updated

Was this helpful?