Skip to main content

πŸ”’ Matrix

One-line summary: 2D arrays β€” master spiral traversal, layer-by-layer rotation, and diagonal/anti-diagonal iteration.


Concept​

Matrix Traversal Matrix GIF

Operations: row-by-row, column-by-column, spiral, diagonal, layer rotation, BFS/DFS on grid.

Key trick: matrix[row][col] β†’ after 90Β° rotation: rotated[col][n-1-row].


Time & Space Complexity​

OperationTimeSpace
Traverse all cellsO(mΒ·n)O(1)
Spiral traversalO(mΒ·n)O(1)
Rotate in-placeO(nΒ²)O(1)
BFS/DFS on gridO(mΒ·n)O(mΒ·n)

Common Patterns​

Spiral Order​

function spiralOrder(matrix) {
const result = [];
let top=0, bottom=matrix.length-1, left=0, right=matrix[0].length-1;
while (top<=bottom && left<=right) {
for (let i=left; i<=right; i++) result.push(matrix[top][i]); top++;
for (let i=top; i<=bottom; i++) result.push(matrix[i][right]); right--;
if (top<=bottom) { for (let i=right; i>=left; i--) result.push(matrix[bottom][i]); bottom--; }
if (left<=right) { for (let i=bottom; i>=top; i--) result.push(matrix[i][left]); left++; }
}
return result;
}

Pascal's Triangle Row​

function getRow(rowIndex) {
const row = new Array(rowIndex+1).fill(0); row[0]=1;
for (let i=1; i<=rowIndex; i++)
for (let j=i; j>0; j--) row[j] += row[j-1];
return row;
}

Pitfalls​

  • Spiral: guard top <= bottom and left <= right before reverse passes
  • BFS on grid: mark visited immediately when enqueuing, not when dequeuing
  • In-place rotation: transpose first, then reverse each row

Practice Problems​

ProblemDifficultySolution
LC 54 β€” Spiral MatrixMediumView Solution
LC 59 β€” Spiral Matrix IIMediumView Solution
LC 118 β€” Pascal's TriangleEasyView Solution
LC 119 β€” Pascal's Triangle IIEasyView Solution
LC 48 β€” Rotate ImageMedium
LC 73 β€” Set Matrix ZeroesMedium
LC 733 β€” Flood FillEasy
LC 74 β€” Search a 2D MatrixMedium
LC 240 β€” Search a 2D Matrix IIMedium
CC β€” Matrix Rotation (MTRNSFRM)Medium
LC 542 β€” 01 MatrixMedium
LC 36 β€” Valid SudokuMedium
LC 37 β€” Sudoku SolverHard
LC 79 β€” Word SearchMedium
LC 130 β€” Surrounded RegionsMedium
LC 200 β€” Number of IslandsMedium
LC 212 β€” Word Search IIHard
LC 221 β€” Maximal SquareMedium
LC 289 β€” Game of LifeMedium
LC 378 β€” Kth Smallest Element in a Sorted MatrixMedium
LC 463 β€” Island PerimeterEasy
LC 498 β€” Diagonal TraverseMedium
LC 695 β€” Max Area of IslandMedium
LC 766 β€” Toeplitz MatrixEasy
LC 867 β€” Transpose MatrixEasy
LC 885 β€” Spiral Matrix IIIMedium
LC 994 β€” Rotting OrangesMedium
LC 1091 β€” Shortest Path in Binary MatrixMedium
LC 1329 β€” Sort the Matrix DiagonallyMedium
LC 1380 β€” Lucky Numbers in a MatrixEasy
LC 1572 β€” Matrix Diagonal SumEasy
LC 1905 β€” Count Sub IslandsMedium
CC β€” Matrix Multiplication (MATMUL)Medium
CC β€” Grid Paths (GRIDPATH)Medium
CC β€” 2D Array Sum (ARRAY2D)Easy

  • Two Pointers β€” converging pointers on matrix rows/columns
  • Graphs β€” BFS/DFS on grid = graph traversal
  • Binary Search β€” 2D sorted matrix search

← Back to Home Β· Β© sparshjaswal