Master 2D arrays and matrix algorithms used in competitive programming and interviews.
0 / 5 topics completed
01
Introduction to Matrix
A Matrix is a 2D array arranged in rows and columns. It is one of the most versatile data structures, used in image processing, graph representation, dynamic programming, and much more. An M × N matrix has M rows and N columns.
Representation in Memory
In most languages, a matrix is stored as an array of arrays. Element at row i, column j is accessed as matrix[i][j] in O(1) time.
A 3×3 matrix: matrix[0][0] is top-left, matrix[2][2] is bottom-right.
If an element is 0, set its entire row and column to 0. Key insight: record which rows/columns need zeroing before modifying, to avoid false propagation.
Practice: Operations
What is the result of transposing the matrix [[1,2],[3,4]]?
Matrices appear in some of the most important algorithmic problems across domains.
1. Graph Representation (Adjacency Matrix)
An N×N boolean matrix where matrix[i][j] = 1 means there's an edge between node i and node j. Trade-off: O(1) edge lookup but O(N²) space.
2. Dynamic Programming
Many DP problems use a 2D table — Longest Common Subsequence, Edit Distance, Unique Paths. The matrix stores subproblem results for bottom-up computation.
3. Island / Flood Fill (BFS/DFS)
Grid problems like "Number of Islands" treat the matrix as a graph. DFS/BFS from each unvisited cell, marking visited cells to avoid re-processing.
4. Search in Sorted Matrix
In a matrix where rows and columns are sorted, start at the top-right corner. If target is smaller, move left; if larger, move down. This gives O(M+N) search.
💡
The "top-right corner" search trick is a favorite FAANG interview pattern. It eliminates one row or one column per step, giving optimal O(M+N) without binary search.
05
Practice Exercises
Test your understanding of matrix concepts.
Exercise 1: Spiral Matrix
Given matrix [[1,2,3],[4,5,6],[7,8,9]], what is the spiral order output?
Answer: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Explanation: Top row left→right: 1,2,3. Right column top→bottom: 6,9. Bottom row right→left: 8,7. Left column bottom→top: 4. Center: 5.
Exercise 2: Rotate 90°
After rotating [[1,2],[3,4]] 90° clockwise in-place, what is the result?
Answer: [[3,1],[4,2]]
Explanation: Transpose → [[1,3],[2,4]]. Reverse each row → [[3,1],[4,2]].
Exercise 3: Search in Sorted Matrix
In matrix [[1,4,7],[2,5,8],[3,6,9]] (rows and columns sorted), how many steps does it take to find 6 using the top-right corner approach?