← Back to libraryQuestion 106 of 273
⌨️Java CodingAdvanced

Spiral Order Traversal of a Matrix

📌 Definition:

Return all elements of a matrix in spiral order — right across the top, down the right side, left across the bottom, up the left side, inward (e.g. [[1,2,3],[4,5,6],[7,8,9]] -> 1,2,3,6,9,8,7,4,5).

📖 Detailed Explanation:

Maintain four boundaries (top, bottom, left, right) and peel one layer per loop: traverse the top row, right column, bottom row, and left column, shrinking the boundaries after each. Guard the bottom/left passes so single rows/columns are not double-counted. O(m * n).

💻 Solutions:
public static List<Integer> spiral(int[][] m) {
    List<Integer> out = new ArrayList<>();
    if (m.length == 0) return out;
    int top = 0, bottom = m.length - 1, left = 0, right = m[0].length - 1;
    while (top <= bottom && left <= right) {
        for (int j = left; j <= right; j++) out.add(m[top][j]);
        top++;
        for (int i = top; i <= bottom; i++) out.add(m[i][right]);
        right--;
        if (top <= bottom) {
            for (int j = right; j >= left; j--) out.add(m[bottom][j]);
            bottom--;
        }
        if (left <= right) {
            for (int i = bottom; i >= top; i--) out.add(m[i][left]);
            left++;
        }
    }
    return out;
}
function spiral(m) {
  const out = [];
  if (m.length === 0) return out;
  let top = 0, bottom = m.length - 1, left = 0, right = m[0].length - 1;
  while (top <= bottom && left <= right) {
    for (let j = left; j <= right; j++) out.push(m[top][j]);
    top++;
    for (let i = top; i <= bottom; i++) out.push(m[i][right]);
    right--;
    if (top <= bottom) {
      for (let j = right; j >= left; j--) out.push(m[bottom][j]);
      bottom--;
    }
    if (left <= right) {
      for (let i = bottom; i >= top; i--) out.push(m[i][left]);
      left++;
    }
  }
  return out;
}
def spiral(m):
    out = []
    if not m:
        return out
    top, bottom, left, right = 0, len(m) - 1, 0, len(m[0]) - 1
    while top <= bottom and left <= right:
        for j in range(left, right + 1):
            out.append(m[top][j])
        top += 1
        for i in range(top, bottom + 1):
            out.append(m[i][right])
        right -= 1
        if top <= bottom:
            for j in range(right, left - 1, -1):
                out.append(m[bottom][j])
            bottom -= 1
        if left <= right:
            for i in range(bottom, top - 1, -1):
                out.append(m[i][left])
            left += 1
    return out
🔑 Key Points:
  • Four shrinking boundaries: top, bottom, left, right
  • Peel a layer per iteration
  • Guard against re-visiting a single row/column
  • O(m*n) time
🌍 Real-World Example:

Spiral traversal appears in image-processing scans and any layered grid walk; interviewers use it to test careful boundary management.

🎯 Scenario-Based Interview Question:

For a single-row matrix [[1,2,3]] a candidate's code prints 1,2,3,2. What is missing?