π’ Matrix
One-line summary: 2D arrays β master spiral traversal, layer-by-layer rotation, and diagonal/anti-diagonal iteration.
Conceptβ
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β
| Operation | Time | Space |
|---|---|---|
| Traverse all cells | O(mΒ·n) | O(1) |
| Spiral traversal | O(mΒ·n) | O(1) |
| Rotate in-place | O(nΒ²) | O(1) |
| BFS/DFS on grid | O(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 <= bottomandleft <= rightbefore reverse passes - BFS on grid: mark visited immediately when enqueuing, not when dequeuing
- In-place rotation: transpose first, then reverse each row
Practice Problemsβ
Related Topicsβ
- 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