Matrices & 2D Arrays
📖 Concept
A matrix (2D array) is an array of arrays — representing grids, tables, images, game boards, and graph adjacency.
Key concepts:
- Access:
matrix[row][col]— O(1) - Dimensions: rows =
matrix.length, cols =matrix[0].length - Total elements: rows × cols
Common matrix patterns in interviews:
- Traversal: Row-wise, column-wise, diagonal, spiral
- Search: Binary search in sorted matrix
- DFS/BFS: Island counting, flood fill, shortest path in grid
- In-place modification: Rotate 90°, set zeroes
- Dynamic programming: Grid paths, minimum path sum
Direction arrays (essential for grid problems):
// 4 directions: up, down, left, right
const dirs = [[-1,0], [1,0], [0,-1], [0,1]];
// 8 directions: include diagonals
const dirs8 = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]];
🏠 Real-world analogy: A spreadsheet is a 2D array — rows and columns with data at each cell. Image processing works on 2D pixel matrices. Game boards (chess, sudoku) are 2D grids.
💻 Code Example
1// CREATE AND TRAVERSE A MATRIX2const matrix = [3 [1, 2, 3],4 [4, 5, 6],5 [7, 8, 9]6];78// Row-wise traversal9for (let r = 0; r < matrix.length; r++) {10 for (let c = 0; c < matrix[0].length; c++) {11 console.log(matrix[r][c]);12 }13}1415// SPIRAL ORDER TRAVERSAL16function spiralOrder(matrix: number[][]): number[] {17 const result: number[] = [];18 let top = 0, bottom = matrix.length - 1;19 let left = 0, right = matrix[0].length - 1;2021 while (top <= bottom && left <= right) {22 for (let i = left; i <= right; i++) result.push(matrix[top][i]);23 top++;24 for (let i = top; i <= bottom; i++) result.push(matrix[i][right]);25 right--;26 if (top <= bottom) {27 for (let i = right; i >= left; i--) result.push(matrix[bottom][i]);28 bottom--;29 }30 if (left <= right) {31 for (let i = bottom; i >= top; i--) result.push(matrix[i][left]);32 left++;33 }34 }35 return result;36}3738// ROTATE MATRIX 90° CLOCKWISE — In-place O(1) space39function rotate(matrix: number[][]): void {40 const n = matrix.length;41 // Step 1: Transpose (swap rows and columns)42 for (let i = 0; i < n; i++) {43 for (let j = i + 1; j < n; j++) {44 [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];45 }46 }47 // Step 2: Reverse each row48 for (const row of matrix) row.reverse();49}5051// COUNT ISLANDS — Grid DFS52function numIslands(grid: string[][]): number {53 let count = 0;54 const rows = grid.length, cols = grid[0].length;55 const dirs = [[0,1],[0,-1],[1,0],[-1,0]];5657 function dfs(r: number, c: number): void {58 if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] !== '1') return;59 grid[r][c] = '0'; // Mark visited60 for (const [dr, dc] of dirs) dfs(r + dr, c + dc);61 }6263 for (let r = 0; r < rows; r++) {64 for (let c = 0; c < cols; c++) {65 if (grid[r][c] === '1') { count++; dfs(r, c); }66 }67 }68 return count;69}7071// SEARCH IN SORTED MATRIX — O(m + n)72function searchMatrix(matrix: number[][], target: number): boolean {73 let row = 0, col = matrix[0].length - 1; // Start top-right74 while (row < matrix.length && col >= 0) {75 if (matrix[row][col] === target) return true;76 if (matrix[row][col] > target) col--;77 else row++;78 }79 return false;80}
🏋️ Practice Exercise
Practice Problems (Easy → Hard):
- Traverse a matrix in spiral order
- Rotate a matrix 90 degrees clockwise in-place
- Set entire row and column to 0 if any element is 0
- Count the number of islands in a grid (connected 1s)
- Search for a target in a row-wise and column-wise sorted matrix
- Find the shortest path in a binary maze (BFS)
- Word search — find if a word exists in a grid (backtracking)
- Flood fill (paint bucket tool in image editors)
- Maximum sum rectangle in a 2D matrix
- Compute the diagonal sum of a matrix
⚠️ Common Mistakes
Confusing row and column indices — matrix[row][col], not matrix[x][y]
Not checking bounds before accessing neighbors — always verify r >= 0, r < rows, c >= 0, c < cols
Forgetting to mark visited cells in grid DFS/BFS — leads to infinite loops
Modifying the input grid when the problem doesn't allow it — use a visited set instead
Creating a matrix with shared row references —
new Array(3).fill(new Array(3).fill(0))shares the SAME inner array
💼 Interview Questions
🎤 Mock Interview
Practice a live interview for Matrices & 2D Arrays