Last updated on March 2nd, 2025 at 07:08 pm
Here, we see a Spiral Matrix LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.
List of all LeetCode Solution
Topics
Array
Companies
Google, Microsoft, Uber
Level of Question
Medium

Spiral Matrix LeetCode Solution
Table of Contents
1. Problem Statement
Given an m x n
matrix
, return all elements of the matrix
in spiral order.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
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]
2. Coding Pattern Used in Solution
The coding pattern used in all the provided implementations is Matrix Traversal. This pattern involves systematically traversing a 2D matrix in a specific order (in this case, a spiral order).
3. Code Implementation in Different Languages
3.1 Spiral Matrix C++
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int>res; if(matrix.size() == 0) return res; int rs = 0, re = matrix.size() - 1, cs = 0, ce = matrix[0].size() - 1; while(rs <= re && cs <= ce) { for(int i = cs; i <= ce; i++) res.push_back(matrix[rs][i]); rs++; for(int i = rs; i <= re; i++) res.push_back(matrix[i][ce]); ce--; for(int i = ce; i >= cs && rs <= re; i--) res.push_back(matrix[re][i]); re--; for(int i = re; i >= rs && cs <= ce; i--) res.push_back(matrix[i][cs]); cs++; } return res; } };
3.2 Spiral Matrix Java
class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> list=new ArrayList<>(); int left=0,right=matrix[0].length; int top=0,bottom=matrix.length; while(left<right && top<bottom){ for(int i=left;i<right;i++){ list.add(matrix[top][i]); } top+=1; for(int i=top;i<bottom;i++){ list.add(matrix[i][right-1]); } right-=1; if (!(left<right && top<bottom)){ break; } for(int i=right-1;i>left;i--){ list.add(matrix[bottom-1][i]); } bottom-=1; for(int i=bottom;i>=top;i--){ list.add(matrix[i][left]); } left+=1; } return list; } }
3.3 Spiral Matrix JavaScript
var spiralOrder = function(matrix) { const res = [] while(matrix.length){ const first = matrix.shift() res.push(...first) for(const m of matrix){ let val = m.pop() if(val) res.push(val) m.reverse() } matrix.reverse() } return res };
3.4 Spiral Matrix Python
class Solution(object): def spiralOrder(self, matrix): return matrix and list(matrix.pop(0)) + self.spiralOrder(zip(*matrix)[::-1])
4. Time and Space Complexity
Time Complexity | Space Complexity | |
C++ | O(m * n) | O(1) |
Java | O(m * n) | O(1) |
JavaScript | O(m * n) | O(m * n) |
Python | O(m * n) | O(m * n) |