54. Spiral Matrix 🌐
Difficulty: Medium - Tags: Matrix, Simulation
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.lengthn == matrix[i].length1 <= 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
Initialization:
Define four boundary variables:
top,bottom,left, andright.
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.
Result:
Stop traversal when
top > bottomorleft > 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?