Spiral Matrix — Direction Array Simulation [Google, Meta, Amazon]

Sanjeev SharmaSanjeev Sharma
2 min read

Advertisement

Problem Statement

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

Input:

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

Intuition — Boundary Shrinking

Maintain four boundaries: top, bottom, left, right. Walk right → down → left → up, shrinking each boundary after traversal.

C++ Solution

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int top=0, bottom=matrix.size()-1, left=0, right=matrix[0].size()-1;
        vector<int> res;
        while (top <= bottom && left <= right) {
            for (int c = left; c <= right; c++) res.push_back(matrix[top][c]);
            top++;
            for (int r = top; r <= bottom; r++) res.push_back(matrix[r][right]);
            right--;
            if (top <= bottom) {
                for (int c = right; c >= left; c--) res.push_back(matrix[bottom][c]);
                bottom--;
            }
            if (left <= right) {
                for (int r = bottom; r >= top; r--) res.push_back(matrix[r][left]);
                left++;
            }
        }
        return res;
    }
};

Python Solution

def spiralOrder(matrix):
    res = []
    top, bottom, left, right = 0, len(matrix)-1, 0, len(matrix[0])-1
    while top <= bottom and left <= right:
        for c in range(left, right+1): res.append(matrix[top][c])
        top += 1
        for r in range(top, bottom+1): res.append(matrix[r][right])
        right -= 1
        if top <= bottom:
            for c in range(right, left-1, -1): res.append(matrix[bottom][c])
            bottom -= 1
        if left <= right:
            for r in range(bottom, top-1, -1): res.append(matrix[r][left])
            left += 1
    return res

Java Solution

class Solution {
    public List<Integer> spiralOrder(int[][] m) {
        List<Integer> res = new ArrayList<>();
        int top=0, bottom=m.length-1, left=0, right=m[0].length-1;
        while (top<=bottom && left<=right) {
            for(int c=left;c<=right;c++) res.add(m[top][c]); top++;
            for(int r=top;r<=bottom;r++) res.add(m[r][right]); right--;
            if(top<=bottom){for(int c=right;c>=left;c--) res.add(m[bottom][c]); bottom--;}
            if(left<=right){for(int r=bottom;r>=top;r--) res.add(m[r][left]); left++;}
        }
        return res;
    }
}

Complexity: O(m*n) time, O(1) extra space

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro