Matrix Coding Problems: 184 Questions with Solutions
184 matrix coding problems — 32 easy · 102 medium · 50 hard — with solutions in 13 languages. Plus a step-by-step walkthrough and a 8-day plan.
- Problems: 184
- By difficulty: 32 easy · 102 medium · 50 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.
New to matrix? Read the Matrix and Grid Traversal tutorial first.
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 184 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 170 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 (32)
- Design Neighbor Sum Service Array, Hash Table, Simulation
- Available Captures for Rook Array, Simulation
- Surface Area of 3D Shapes Array, Math, Geometry
- Check if Every Row and Column Contains All Numbers Array, Hash Table
- 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 (102)
- Range Sum Query 2D - Immutable Array, Prefix Sum, Design
- Spiral Matrix IV Linked List, Simulation, Array
- Flip Columns For Maximum Number of Equal Rows Array, Hash Table
- Count Islands With Total Value Divisible by K Array, Depth-First Search, Breadth-First Search
- Find Minimum Time to Reach Last Room II Array, Graph, Heap (Priority Queue)
- Find Minimum Time to Reach Last Room I Array, Graph, Heap (Priority Queue)
- Find a Safe Walk Through a Grid Array, Breadth-First Search, Graph
- Disconnect Path in a Binary Matrix by at Most One Flip Array, Dynamic Programming, Depth-First Search
- K Highest Ranked Items Within a Price Range Array, Breadth-First Search, Sorting
- Coloring A Border Array, Depth-First Search, Breadth-First Search
- Knight Walk Breadth-First Search
- Maximum Amount of Money Robot Can Earn Array, Dynamic Programming
- Count Paths With the Given XOR Value Array, Dynamic Programming, Bit Manipulation
- Maximum Points Tourist Can Earn Array, Dynamic Programming
- Maximum Difference Score in a Grid Array, Dynamic Programming
- Minimum Number of Operations to Satisfy Conditions Array, Dynamic Programming
- Minimum Path Cost in a Grid Array, Dynamic Programming
- Gold Mine Problem Array, Dynamic Programming
- Largest Submatrix With Rearrangements Array, Greedy, Sorting
- Count Unguarded Cells in the Grid Array, Simulation
- Largest Magic Square Array, Prefix Sum
- Get Biggest Three Rhombus Sums in a Grid Array, Prefix Sum, Sorting
- Valid Tic-Tac-Toe State Array, Simulation
- Queens That Can Attack the King Array, Simulation
- Minesweeper Array, Breadth-First Search, Depth-First Search
- Battleships in a Board Array, Depth-First Search
- Minimum Swaps to Arrange a Binary Grid Array, Greedy
- Largest 1-Bordered Square Array, Dynamic Programming
- Image Overlap Array, Enumeration
- Maximum Non Negative Product in a Matrix Array, Dynamic Programming
- Minimum Operations to Write the Letter Y on a Grid Array, Hash Table, Counting
- Difference of Number of Distinct Values on Diagonals Array, Hash Table
- Maximum Sum of an Hourglass Array, Prefix Sum
- Diagonal Traverse II Array, Sorting
- Nearest Exit from Entrance in Maze Array, Breadth-First Search
- Check if There is a Valid Path in a Grid Breadth-First Search, Depth-First Search, Union Find
- Minimize the Difference Between Target and Chosen Elements Array, Dynamic Programming
- Out of Boundary Paths Dynamic Programming
- Score After Flipping Matrix Array, Greedy, Bit Manipulation
- Count Submatrices With All Ones Array, Stack, Monotonic Stack
- Median in a Row-Wise Sorted Matrix Array, Binary Search
- Maximum Side Length of a Square with Sum Less than or Equal to Threshold Array, Binary Search, Prefix Sum
- Maximum Rows Covered by Columns Array, Bit Manipulation, Enumeration
- Minimum Operations to Make a Uni-Value Grid Array, Math, Sorting
- Grid Game Array, Prefix Sum
- 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 (50)
- Stamping the Grid Array, Greedy, Prefix Sum
- Rank Transform of a Matrix Array, Union Find, Graph
- Last Day Where You Can Still Cross Array, Binary Search, Depth-First Search
- Bricks Falling When Hit Array, Union Find
- Minimum Number of Visited Cells in a Grid Array, Dynamic Programming, Stack
- Strange Printer II Array, Graph, Topological Sort
- Minimum Number of Flips to Convert Binary Matrix to Zero Matrix Array, Hash Table, Bit Manipulation
- Minimum Moves to Move a Box to Their Target Location Array, Breadth-First Search, Heap (Priority Queue)
- Contain Virus Array, Depth-First Search, Breadth-First Search
- Cut Off Trees for Golf Event Array, Breadth-First Search, Heap (Priority Queue)
- Length of Longest V-Shaped Diagonal Segment Array, Dynamic Programming, Memoization
- Select Cells in Grid With Maximum Score Array, Dynamic Programming, Bit Manipulation
- Maximum Strictly Increasing Cells in a Matrix Array, Hash Table, Binary Search
- Check if There Is a Valid Parentheses String Path Array, Dynamic Programming
- Minimum Cost to Connect Two Groups of Points Array, Dynamic Programming, Bit Manipulation
- Word Search II String, Backtracking, Trie
- Sudoku Solver Array, Hash Table, Backtracking
- Minimum Cost to Make at Least One Valid Path in a Grid Breadth-First Search, Graph, Shortest Path
- Shortest Path in a Grid with Obstacles Elimination Array, Breadth-First Search
- Transform to Chessboard Array, Math, Bit Manipulation
- Minimum Moves to Reach Target with Rotations Array, Breadth-First Search
- Number of Paths with Max Score Array, Dynamic Programming
- Max Sum of Rectangle No Larger Than K Array, Binary Search, Ordered Set
- Shortest Path to Get All Keys Array, Bit Manipulation, Breadth-First Search
- Number of Ways of Cutting a Pizza Array, Dynamic Programming, Prefix Sum
- Maximum Number of Points From Grid Queries Array, Breadth-First Search, Heap (Priority Queue)
- Maximum Students Taking Exam Dynamic Programming, Bit Manipulation, Bitmask
- Find the String with LCP String, Dynamic Programming, Greedy
- 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 159 problems on matrix
- Google 134 problems on matrix
- Microsoft 47 problems on matrix
- Meta 23 problems on matrix
- Adobe 20 problems on matrix
- Uber 11 problems on matrix
- Snapchat 7 problems on matrix
- Directi 6 problems on matrix
- Flipkart 6 problems on matrix
- Nutanix 6 problems on matrix
- Airbnb 5 problems on matrix
- Apple 5 problems on matrix
Next topic: Simulation