Matrix Coding Problems: 107 Questions with Solutions
107 matrix coding problems — 28 easy · 57 medium · 22 hard — with solutions in 13 languages. Plus a step-by-step walkthrough and a 8-day plan.
- Problems: 107
- By difficulty: 28 easy · 57 medium · 22 hard
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
- Cost: Free on every plan; sign in to run and submit
A two-dimensional grid: walk it in spiral order, rotate it in place, search a sorted one, count islands, mark rows and columns. Matrix problems are index bookkeeping with a purpose — keeping (row, column) straight, staying inside the bounds, and choosing between visiting every cell and exploiting the grid's structure.
How matrix works, step by step
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]- A 90° clockwise turn sends the value at (i, j) to (j, 2 − i). Doing that directly needs cycles of four moves; it is simpler as two passes of plain swaps, a transpose and then a mirror of each row.
- Transpose first: swap m[0][1] = 2 with m[1][0] = 4 across the main diagonal. The diagonal cells 1, 5 and 9 map to themselves and never move.
- Swap m[0][2] = 3 with m[2][0] = 7 across the main diagonal. Only cells above the diagonal start a swap, so no pair is swapped back.
- Swap m[1][2] = 6 with m[2][1] = 8 across the main diagonal. The transpose is done: row i now holds what column i held.
- Now mirror each row. Row 0, [1, 4, 7], becomes [7, 4, 1]: its ends swap and the middle stays. Together with the transpose this moves (i, j) to (j, 2 − i), exactly the turn.
- Row 1, [2, 5, 8], becomes [8, 5, 2]. Each row is mirrored on its own, so the rows can be done in any order.
- Row 2, [3, 6, 9], becomes [9, 6, 3], the last swap: every value has reached its rotated place.
- Rotated: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]. The old first column 7, 4, 1, read bottom-up, is the new first row. Every cell is touched a constant number of times: O(n²) time and O(1) extra space.
Matrix study plan
14 of the 107 Matrix problems (4 easy, 7 medium and 3 hard) over 8 days, about 8 h 10 min in all — the pattern first, then easiest to hardest. After that, the other 93 in the full list below are practice at your own pace. Then move on to Simulation.
Day 1
Learn the pattern: read the essentials and step through the walkthrough above, then solve these 3.
- Richest Customer Wealth Easy
- Transpose Matrix Easy
- Matrix Diagonal Sum Easy
Day 2
Medium problems: the same pattern with one twist each. Name the twist before you code.
- Flood Fill Easy
- Spiral Matrix Medium
Day 3
More mediums. Before coding each one, write down what state the pattern keeps and when it changes.
- Rotate Image Medium
- Set Matrix Zeroes Medium
Day 4
More mediums. Before coding each one, write down what state the pattern keeps and when it changes.
- Search a 2D Matrix Medium
- Game of Life Medium
Day 5
More mediums. Before coding each one, write down what state the pattern keeps and when it changes.
- Word Search Medium
- Number of Islands Medium
Day 6
Hard problems: the pattern combined with a second idea. Give each a full attempt before reading the editorial.
- Swim in Rising Water Hard
Day 7
Another hard one. If it beats you after a real attempt, read the editorial, then solve it again tomorrow from memory.
Day 8
Another hard one. If it beats you after a real attempt, read the editorial, then solve it again tomorrow from memory.
- Dungeon Game Hard
Matrix: the essentials
When to reach for it
The input is m × n rows and columns: an image, a game board, a map of land and water, a table sorted along its rows and columns. The question picks the tool. Transforming the whole grid (rotate, transpose, spiral order) is index arithmetic. Anything about connected regions or the fewest moves between cells is a graph search with cells as nodes — see Breadth-First Search.
The pattern
Name the dimensions once, rows = len(grid) and cols = len(grid[0]), and walk neighbours with a list of directions rather than four copied blocks. A 90° clockwise rotation is a transpose followed by reversing each row. To mark cells in place, borrow spare state from the grid itself — the first row and column, or a value outside the input's range — instead of allocating a second grid.
DIRS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
def neighbours(grid, r, c):
rows, cols = len(grid), len(grid[0])
for dr, dc in DIRS:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
yield nr, nc
Cost
Visiting every cell is O(m × n), the floor for most matrix questions. A matrix sorted along rows and columns can be searched in O(m + n) by starting at a corner. In-place transforms use O(1) extra space.
Common mistakes
- Mixing up rows and columns:
grid[r][c]is rowr, columnc, and naming themxandyinvitesgrid[x][y]slips. - Assuming a square grid, so code that works for
n × nbreaks onm × n. - Overwriting a cell whose original value a later step still needs (Game of Life, Set Matrix Zeroes).
- Building rows with
[[0] * n] * min Python, which makes every row the same list.
Start with
- Transpose Matrix: rows become columns.
- Spiral Matrix: four shrinking boundaries.
- Rotate Image: an in-place transform built from two simpler ones.
All matrix problems
Easy (28)
- Delete Greatest Value in Each Row Array, Sorting, Simulation
- Modify the Matrix Array
- Find Champion I Array, Graph
- Prime In Diagonal Array, Math, Number Theory
- Matrix Similarity After Cyclic Shifts Array, Simulation
- Find Missing and Repeated Values Hash Table, Math
- Special Positions in a Binary Matrix Array
- Projection Area of 3D Shapes Array, Math, Geometry
- Matrix Cells in Distance Order Array, Math, Sorting
- Find Winner on a Tic Tac Toe Game Array, Hash Table, Simulation
- Convert 1D Array Into 2D Array Array, Simulation
- Largest Local Values in a Matrix Array
- Row With Maximum Ones Array
- Check if Matrix Is X-Matrix Array
- Determine Whether Matrix Can Be Obtained By Rotation Array
- The K Weakest Rows in a Matrix Array, Binary Search, Sorting
- Shift 2D Grid Array, Simulation
- Lucky Numbers in a Matrix Array
- Count Negative Numbers in a Sorted Matrix Array, Binary Search
- Image Smoother Array
- Flipping an Image Array, Two Pointers, Simulation
- Reshape the Matrix Array, Simulation
- Toeplitz Matrix Array
- Island Perimeter Array
- Flood Fill Array, Depth-First Search, Breadth-First Search
- Richest Customer Wealth Array
- Matrix Diagonal Sum Array
- Transpose Matrix Array, Simulation
Medium (57)
- Count Fertile Pyramids in a Land Array, Dynamic Programming
- Find the Safest Path in a Grid Array, Binary Search, Breadth-First Search
- The Maze II Array, Graph, Breadth-First Search
- Largest Plus Sign Array, Dynamic Programming
- Remove All Ones With Row and Column Flips Array, Bit Manipulation
- Number of Corner Rectangles Array, Math, Dynamic Programming
- Magic Squares In Grid Array, Simulation
- Maximum Number of Fish in a Grid Array, Depth-First Search, Breadth-First Search
- Construct Product Matrix Array, Prefix Sum
- Maximum Number of Moves in a Grid Array, Dynamic Programming, Breadth-First Search
- Map of Highest Peak Array, Breadth-First Search
- Convert an Array Into a 2D Array With Conditions Array, Hash Table
- Check Knight Tour Configuration Array, Depth-First Search, Simulation
- First Completely Painted Row or Column Array, Hash Table
- Rotating the Box Array, Two Pointers, Simulation
- Find All Groups of Farmland Array, Depth-First Search, Breadth-First Search
- Matrix Block Sum Array, Prefix Sum
- Spiral Matrix III Array, Simulation
- Where Will the Ball Fall Array, Simulation, Depth-First Search
- Maximum Matrix Sum Array, Greedy
- Difference Between Ones and Zeros in Row and Column Array, Simulation
- Search a 2D Matrix II Array, Binary Search, Divide and Conquer
- Equal Row and Column Pairs Hash Table, Simulation
- Word Search Array, String, Backtracking
- Pacific Atlantic Water Flow Array, Depth-First Search, Breadth-First Search
- Snakes and Ladders Array, Breadth-First Search
- Path With Minimum Effort Array, Binary Search, Depth-First Search
- Detect Cycles in 2D Grid Array, Depth-First Search, Breadth-First Search
- Number of Distinct Islands Array, Hash Table, Depth-First Search
- Shortest Bridge Array, Depth-First Search, Breadth-First Search
- Count Sub Islands Array, Depth-First Search, Breadth-First Search
- As Far from Land as Possible Array, Dynamic Programming, Breadth-First Search
- Shortest Path in Binary Matrix Array, Breadth-First Search
- Number of Enclaves Array, Depth-First Search, Breadth-First Search
- Kth Smallest Element in a Sorted Matrix Array, Binary Search, Sorting
- Minimum Falling Path Sum Array, Dynamic Programming
- Valid Sudoku Array, Hash Table
- Count Servers that Communicate Array, Depth-First Search, Breadth-First Search
- Number of Closed Islands Array, Depth-First Search, Breadth-First Search
- Surrounded Regions Array, Depth-First Search, Breadth-First Search
- Game of Life Array, Simulation
- Count Square Submatrices with All Ones Array, Dynamic Programming
- Maximal Square Array, Dynamic Programming
- Unique Paths II Array, Dynamic Programming
- Minimum Path Sum Array, Dynamic Programming
- Sort the Matrix Diagonally Array, Sorting
- Max Increase to Keep City Skyline Array, Greedy
- Diagonal Traverse Array, Simulation
- Spiral Matrix II Array, Simulation
- 01 Matrix Array, Breadth-First Search, Dynamic Programming
- Rotting Oranges Array, Breadth-First Search
- Max Area of Island Array, Depth-First Search
- Number of Islands Array, Depth-First Search, Breadth-First Search
- Search a 2D Matrix Array, Binary Search
- Set Matrix Zeroes Array, Hash Table
- Spiral Matrix Array, Simulation
- Rotate Image Array, Math
Hard (22)
- Cherry Pickup II Array, Dynamic Programming
- Paths in Matrix Whose Sum Is Divisible by K Array, Dynamic Programming
- Minimum Time to Visit a Cell In a Grid Array, Graph, Breadth-First Search
- Minimum Number of Days to Disconnect Island Array, Depth-First Search, Breadth-First Search
- Number of Increasing Paths in a Grid Array, Dynamic Programming, Depth-First Search
- Minimum Obstacle Removal to Reach Corner Array, Graph, Breadth-First Search
- Sliding Puzzle Array, Breadth-First Search
- Trapping Rain Water II Array, Heap (Priority Queue), Breadth-First Search
- Escape the Spreading Fire Array, Binary Search, Breadth-First Search
- Grid Illumination Array, Hash Table
- Shortest Distance from All Buildings Array, Breadth-First Search
- Minimum Moves to Spread Stones Over Grid Array, Dynamic Programming, Breadth-First Search
- Making A Large Island Array, Depth-First Search, Breadth-First Search
- Unique Paths III Array, Backtracking, Bit Manipulation
- Number of Submatrices That Sum to Target Array, Hash Table, Prefix Sum
- Longest Increasing Path in a Matrix Array, Dynamic Programming, Depth-First Search
- Maximal Rectangle Array, Stack, Dynamic Programming
- Cherry Pickup Array, Dynamic Programming
- Minimum Falling Path Sum II Array, Dynamic Programming
- Dungeon Game Array, Dynamic Programming
- Find the Kth Smallest Sum of a Matrix With Sorted Rows Array, Binary Search, Heap
- Swim in Rising Water Array, Binary Search, Depth-First Search
Companies that ask matrix problems
- Amazon 93 problems on matrix
- Google 72 problems on matrix
- Microsoft 35 problems on matrix
- Adobe 19 problems on matrix
- Meta 16 problems on matrix
- Uber 9 problems on matrix
- Apple 4 problems on matrix
- Flipkart 4 problems on matrix
- Infosys 4 problems on matrix
- TCS 3 problems on matrix
- Walmart 3 problems on matrix
- Bloomberg 2 problems on matrix
Next topic: Simulation