Matrices
The Matrices Pattern
A 2D grid is a graph whose neighbours are implicit: each cell connects to the cells beside it. Most matrix problems are BFS, DFS or DP with row and column bookkeeping, plus in-place tricks for rotation and traversal.
Interactive problems
Free to open
How do you recognise a matrices problem?
The input is a 2D grid and the question involves islands, regions, flood fill, spiral or diagonal traversal, path counting, or rotating and transposing in place.
What is the time complexity of the matrices pattern?
O(rows × cols) for a full traversal. In-place transformations keep space at O(1) beyond the input.
Matrices practice problems
Each problem pairs a worked explanation with an interactive visualizer you step through yourself, plus the implementation in JavaScript, Python, Java and C++.
Matrices problems by difficulty and complexity
The difficulty, running time and extra space of every matrices solution on this page, as each lesson derives them.
| Lesson | Difficulty | Best | Average | Worst | Space |
|---|---|---|---|---|---|
| Spiral Matrix | Medium | Ω(m·n) | Θ(m·n) | O(m·n) | O(1) |
| Rotate Image | Medium | Ω(n²) | Θ(n²) | O(n²) | O(1) |
| Set Matrix Zeroes | Medium | Ω(m·n) | Θ(m·n) | O(m·n) | O(1) |
Related patterns and concepts
Matrices is one of the 17 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.
Every other coding interview pattern
Depth-First Search · 25 lessons
- Introduction to DFSFree
- DFS FundamentalsFree
- Return Values in DFS
- Invert Binary Tree
- Maximum Depth of Binary Tree
- Path Sum
- Passing Values Down (State)
- Validate Binary Search Tree
- Kth Smallest Element in a BST
- Construct Binary Tree from Preorder and Inorder Traversal
- Binary Tree Tilt
- Diameter of Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Path Sum II
- Longest Univalue Path
- Graphs Overview
- Graph Representation: Adjacency List
- Clone Graph
- Graph Valid Tree
- Matrices as Graphs
- Flood Fill
- Types of DFS (Tree Traversals)
- Number of Islands
- Surrounded Regions
- Pacific Atlantic Water FlowFree
