Interview Cheat Sheets | Matrix Cheat Sheet
December 23rd, 2023
Introduction
This article will serve to further summarize the excellent overview of matrices from the tech interview handbook.
Overview
- A matrix is a 2-dimensional array, often used in dynamic programming or graph traversal problems.
- Matrices can represent graphs, with each cell as a node having 4 neighbors (except edge and corner cells).
Corner Cases:
- Consider empty matrices, 1x1 matrices, and matrices with only one row or column.
Techniques:
-
Creating an empty N x M matrix is crucial for traversal or dynamic programming.
-
An example of creating an empty
m x n
matrix in typescript:function createEmptyMatrix(m: number, n: number): number[][] { return Array.from({ length: m }, () => Array(n).fill(0)); }
-
An example of copying an
m x n
matrix in typescript:function copyMatrix(matrix: number[][]): number[][] { return matrix.map((row) => [...row]); }
-
-
Transposing a matrix involves interchanging its rows and columns.
-
An example of transposing an
m x n
matrix in typescript:function transposeMatrix(matrix: number[][]): number[][] { return matrix[0].map((_, columnIndex) => matrix.map((row) => row[columnIndex]) ); }
-
Essential Questions:
- Set Matrix Zeroes
- Spiral Matrix - My solution
Recommended Practice Questions:
- Rotate Image
- Valid Sudoku