๐ข 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