Matrix and Grid Pattern: Template + 216 LeetCode Problems
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells.
- 32 Easy
- 125 Medium
- 59 Hard
- O(r · c) time
What the matrix and grid pattern is
A grid is a graph that nobody bothered to build: each cell is a node and its neighbours are the adjacent cells, so DFS, BFS and union-find all apply unchanged once you write the neighbour loop as a list of offsets rather than four copied blocks. Flood fill — walk from a cell, claim everything connected to it, repeat from every unclaimed cell — is the shape behind counting islands, enclosing regions and colouring components. Marking visited cells in the grid itself, by overwriting them, saves the extra structure and is usually acceptable; when it is not, a set of coordinate tuples is the fallback. The bounds check belongs at the top of the recursive call rather than before it, so there is one copy of it instead of four. Rotation and spiral problems are a different sub-family: they are index arithmetic, and the reliable way through them is to name the boundaries explicitly — top, bottom, left, right — and shrink them, rather than trying to derive a closed-form index map under pressure.
When to use it
- Cells are connected to their neighbours and you need regions, components or reachability.
- The shortest path through a grid is wanted, which is BFS with four or eight offsets.
- The answer is a distance from the nearest of many sources — one multi-source BFS pass.
- The problem is index mechanics: rotate in place, traverse in spiral order, transpose.
The matrix and grid template in Python
The shape, not a solution to any one problem. Adapt the condition and the summary being maintained; the skeleton stays the same across the 216 problems listed below.
def count_islands(grid):
rows, cols = len(grid), len(grid[0])
def sink(r, c):
if not (0 <= r < rows and 0 <= c < cols) or grid[r][c] != "1":
return # one bounds check, not four
grid[r][c] = "0" # mark in place; no separate seen set
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
sink(r + dr, c + dc)
islands = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1":
islands += 1
sink(r, c)
return islandsComplexity characteristics
- Time
- O(r · c)
- Auxiliary space
- O(r · c) worst case, O(1) when marking in place
Flood fill visits every cell at most once across all of its starting points, because a claimed cell is never re-entered — so counting islands is linear in the number of cells even though it launches a traversal from many of them. The space is the stack or queue, which can hold every cell on a grid that is one large region. Overwriting visited cells in the grid itself removes the separate seen structure entirely, at the cost of destroying the input.
All 216 matrix and grid LeetCode problems
Every problem in the library the matrix and grid pattern applies to, grouped by LeetCode's own difficulty rating. 178 of the 216 carry a complete Python solution with a worked example and complexity analysis; the rest are listed for completeness, with the LeetCode Premium ones marked.
Easy (32)
| # | Problem | Difficulty | Topics |
|---|---|---|---|
| 463 | Island Perimeter | Easy | Depth-First Search, Breadth-First Search, Array +1 |
| 566 | Reshape the Matrix | Easy | Array, Matrix, Simulation |
| 661 | Image Smoother | Easy | Array, Matrix |
| 733 | Flood Fill | Easy | Depth-First Search, Breadth-First Search, Array +1 |
| 422 | Valid Word SquarePremium | Easy | Array, Matrix |
| 766 | Toeplitz Matrix | Easy | Array, Matrix |
| 832 | Flipping an Image | Easy | Bit Manipulation, Array, Two Pointers +2 |
| 867 | Transpose Matrix | Easy | Array, Matrix, Simulation |
| 883 | Projection Area of 3D Shapes | Easy | Geometry, Array, Math +1 |
| 892 | Surface Area of 3D Shapes | Easy | Geometry, Array, Math +1 |
| 999 | Available Captures for Rook | Easy | Array, Matrix, Simulation |
| 1030 | Matrix Cells in Distance Order | Easy | Geometry, Array, Math +2 |
| 1260 | Shift 2D Grid | Easy | Array, Matrix, Simulation |
| 1275 | Find Winner on a Tic Tac Toe Game | Easy | Array, Hash Table, Matrix +1 |
| 1337 | The K Weakest Rows in a Matrix | Easy | Array, Binary Search, Matrix +2 |
| 1351 | Count Negative Numbers in a Sorted Matrix | Easy | Array, Binary Search, Matrix |
| 1380 | Lucky Numbers in a Matrix | Easy | Array, Matrix |
| 1572 | Matrix Diagonal Sum | Easy | Array, Matrix |
| 1582 | Special Positions in a Binary Matrix | Easy | Array, Matrix |
| 1672 | Richest Customer Wealth | Easy | Array, Matrix |
| 1886 | Determine Whether Matrix Can Be Obtained By Rotation | Easy | Array, Matrix |
| 2022 | Convert 1D Array Into 2D Array | Easy | Array, Matrix, Simulation |
| 2133 | Check if Every Row and Column Contains All Numbers | Easy | Array, Hash Table, Matrix |
| 2319 | Check if Matrix Is X-Matrix | Easy | Array, Matrix |
| 2373 | Largest Local Values in a Matrix | Easy | Array, Matrix |
| 2500 | Delete Greatest Value in Each Row | Easy | Array, Matrix, Sorting +2 |
| 2614 | Prime In Diagonal | Easy | Array, Math, Matrix +1 |
| 2639 | Find the Width of Columns of a Grid | Easy | Array, Matrix |
| 2643 | Row With Maximum Ones | Easy | Array, Matrix |
| 2923 | Find Champion I | Easy | Array, Matrix |
| 2946 | Matrix Similarity After Cyclic Shifts | Easy | Array, Math, Matrix +1 |
| 2965 | Find Missing and Repeated Values | Easy | Array, Hash Table, Math +1 |
Medium (125)
| # | Problem | Difficulty | Topics |
|---|---|---|---|
| 36 | Valid Sudoku | Medium | Array, Hash Table, Matrix |
| 48 | Rotate Image | Medium | Array, Math, Matrix |
| 54 | Spiral Matrix | Medium | Array, Matrix, Simulation |
| 59 | Spiral Matrix II | Medium | Array, Matrix, Simulation |
| 63 | Unique Paths II | Medium | Array, Dynamic Programming, Matrix |
| 64 | Minimum Path Sum | Medium | Array, Dynamic Programming, Matrix |
| 73 | Set Matrix Zeroes | Medium | Array, Hash Table, Matrix |
| 74 | Search a 2D Matrix | Medium | Array, Binary Search, Matrix |
| 79 | Word Search | Medium | Depth-First Search, Array, String +2 |
| 130 | Surrounded Regions | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 200 | Number of Islands | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 221 | Maximal Square | Medium | Array, Dynamic Programming, Matrix |
| 240 | Search a 2D Matrix II | Medium | Array, Binary Search, Divide and Conquer +1 |
| 289 | Game of Life | Medium | Array, Matrix, Simulation |
| 304 | Range Sum Query 2D - Immutable | Medium | Design, Array, Matrix +1 |
| 378 | Kth Smallest Element in a Sorted Matrix | Medium | Array, Binary Search, Matrix +2 |
| 417 | Pacific Atlantic Water Flow | Medium | Depth-First Search, Breadth-First Search, Array +1 |
| 419 | Battleships in a Board | Medium | Depth-First Search, Array, Matrix |
| 427 | Construct Quad Tree | Medium | Tree, Array, Divide and Conquer +1 |
| 498 | Diagonal Traverse | Medium | Array, Matrix, Simulation |
| 529 | Minesweeper | Medium | Depth-First Search, Breadth-First Search, Array +1 |
| 542 | 01 Matrix | Medium | Breadth-First Search, Array, Dynamic Programming +1 |
| 695 | Max Area of Island | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 909 | Snakes and Ladders | Medium | Breadth-First Search, Array, Matrix |
| 994 | Rotting Oranges | Medium | Breadth-First Search, Array, Matrix |
| 1926 | Nearest Exit from Entrance in Maze | Medium | Breadth-First Search, Array, Matrix |
| 2352 | Equal Row and Column Pairs | Medium | Array, Hash Table, Matrix +1 |
| 286 | Walls and GatesPremium | Medium | Breadth-First Search, Array, Matrix |
| 308 | Range Sum Query 2D - MutablePremium | Medium | Design, Binary Indexed Tree, Segment Tree +2 |
| 311 | Sparse Matrix MultiplicationPremium | Medium | Array, Hash Table, Matrix |
| 348 | Design Tic-Tac-ToePremium | Medium | Design, Array, Hash Table +2 |
| 361 | Bomb EnemyPremium | Medium | Array, Dynamic Programming, Matrix |
| 490 | The MazePremium | Medium | Depth-First Search, Breadth-First Search, Array +1 |
| 505 | The Maze IIPremium | Medium | Depth-First Search, Breadth-First Search, Graph +4 |
| 531 | Lonely Pixel IPremium | Medium | Array, Hash Table, Matrix |
| 533 | Lonely Pixel IIPremium | Medium | Array, Hash Table, Matrix |
| 562 | Longest Line of Consecutive One in MatrixPremium | Medium | Array, Dynamic Programming, Matrix |
| 723 | Candy CrushPremium | Medium | Array, Two Pointers, Matrix +1 |
| 750 | Number Of Corner RectanglesPremium | Medium | Array, Math, Dynamic Programming +1 |
| 794 | Valid Tic-Tac-Toe State | Medium | Array, Matrix |
| 807 | Max Increase to Keep City Skyline | Medium | Greedy, Array, Matrix |
| 835 | Image Overlap | Medium | Array, Matrix |
| 840 | Magic Squares In Grid | Medium | Array, Hash Table, Math +1 |
| 861 | Score After Flipping Matrix | Medium | Greedy, Bit Manipulation, Array +1 |
| 885 | Spiral Matrix III | Medium | Array, Matrix, Simulation |
| 931 | Minimum Falling Path Sum | Medium | Array, Dynamic Programming, Matrix |
| 934 | Shortest Bridge | Medium | Depth-First Search, Breadth-First Search, Array +1 |
| 959 | Regions Cut By Slashes | Medium | Depth-First Search, Breadth-First Search, Union Find +3 |
| 1020 | Number of Enclaves | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 1034 | Coloring A Border | Medium | Depth-First Search, Breadth-First Search, Array +1 |
| 1072 | Flip Columns For Maximum Number of Equal Rows | Medium | Array, Hash Table, Matrix |
| 1091 | Shortest Path in Binary Matrix | Medium | Breadth-First Search, Array, Matrix |
| 1102 | Path With Maximum Minimum ValuePremium | Medium | Depth-First Search, Breadth-First Search, Union Find +4 |
| 1139 | Largest 1-Bordered Square | Medium | Array, Dynamic Programming, Matrix |
| 1162 | As Far from Land as Possible | Medium | Breadth-First Search, Array, Dynamic Programming +1 |
| 1198 | Find Smallest Common Element in All RowsPremium | Medium | Array, Hash Table, Binary Search +2 |
| 1219 | Path with Maximum Gold | Medium | Array, Backtracking, Matrix |
| 1222 | Queens That Can Attack the King | Medium | Array, Matrix, Simulation |
| 1253 | Reconstruct a 2-Row Binary Matrix | Medium | Greedy, Array, Matrix |
| 1254 | Number of Closed Islands | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 1267 | Count Servers that Communicate | Medium | Depth-First Search, Breadth-First Search, Union Find +3 |
| 1277 | Count Square Submatrices with All Ones | Medium | Array, Dynamic Programming, Matrix |
| 1292 | Maximum Side Length of a Square with Sum Less than or Equal to Threshold | Medium | Array, Binary Search, Matrix +1 |
| 1314 | Matrix Block Sum | Medium | Array, Matrix, Prefix Sum |
| 1329 | Sort the Matrix Diagonally | Medium | Array, Matrix, Sorting |
| 1391 | Check if There is a Valid Path in a Grid | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 1428 | Leftmost Column with at Least a OnePremium | Medium | Array, Binary Search, Interactive +1 |
| 1476 | Subrectangle Queries | Medium | Design, Array, Matrix |
| 1504 | Count Submatrices With All Ones | Medium | Stack, Array, Dynamic Programming +2 |
| 1536 | Minimum Swaps to Arrange a Binary Grid | Medium | Greedy, Array, Matrix |
| 1559 | Detect Cycles in 2D Grid | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 1594 | Maximum Non Negative Product in a Matrix | Medium | Array, Dynamic Programming, Matrix |
| 1605 | Find Valid Matrix Given Row and Column Sums | Medium | Greedy, Array, Matrix |
| 1631 | Path With Minimum Effort | Medium | Depth-First Search, Breadth-First Search, Union Find +4 |
| 1706 | Where Will the Ball Fall | Medium | Array, Matrix, Simulation |
| 1727 | Largest Submatrix With Rearrangements | Medium | Greedy, Array, Matrix +1 |
| 1730 | Shortest Path to Get FoodPremium | Medium | Breadth-First Search, Array, Matrix |
| 1738 | Find Kth Largest XOR Coordinate Value | Medium | Bit Manipulation, Array, Divide and Conquer +5 |
| 1765 | Map of Highest Peak | Medium | Breadth-First Search, Array, Matrix |
| 1778 | Shortest Path in a Hidden GridPremium | Medium | Depth-First Search, Breadth-First Search, Array +2 |
| 1810 | Minimum Path Cost in a Hidden GridPremium | Medium | Depth-First Search, Breadth-First Search, Graph +5 |
| 1820 | Maximum Number of Accepted InvitationsPremium | Medium | Depth-First Search, Graph, Array +1 |
| 1861 | Rotating the Box | Medium | Array, Two Pointers, Matrix |
| 1878 | Get Biggest Three Rhombus Sums in a Grid | Medium | Array, Math, Matrix +3 |
| 1895 | Largest Magic Square | Medium | Array, Matrix, Prefix Sum |
| 1901 | Find a Peak Element II | Medium | Array, Binary Search, Matrix |
| 1905 | Count Sub Islands | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 1914 | Cyclically Rotating a Grid | Medium | Array, Matrix, Simulation |
| 1937 | Maximum Number of Points with Cost | Medium | Array, Dynamic Programming, Matrix |
| 1958 | Check if Move is Legal | Medium | Array, Enumeration, Matrix |
| 1975 | Maximum Matrix Sum | Medium | Greedy, Array, Matrix |
| 1981 | Minimize the Difference Between Target and Chosen Elements | Medium | Array, Dynamic Programming, Matrix |
| 1992 | Find All Groups of Farmland | Medium | Depth-First Search, Breadth-First Search, Array +1 |
| 2017 | Grid Game | Medium | Array, Matrix, Prefix Sum |
| 2018 | Check if Word Can Be Placed In Crossword | Medium | Array, Enumeration, Matrix |
| 2033 | Minimum Operations to Make a Uni-Value Grid | Medium | Array, Math, Matrix +1 |
| 2061 | Number of Spaces Cleaning Robot CleanedPremium | Medium | Array, Matrix, Simulation |
| 2125 | Number of Laser Beams in a Bank | Medium | Array, Math, String +1 |
| 2128 | Remove All Ones With Row and Column FlipsPremium | Medium | Bit Manipulation, Array, Math +1 |
| 2146 | K Highest Ranked Items Within a Price Range | Medium | Breadth-First Search, Array, Matrix +2 |
| 2174 | Remove All Ones With Row and Column Flips IIPremium | Medium | Bit Manipulation, Breadth-First Search, Array +1 |
| 2245 | Maximum Trailing Zeros in a Cornered Path | Medium | Array, Matrix, Prefix Sum |
| 2257 | Count Unguarded Cells in the Grid | Medium | Array, Matrix, Simulation |
| 2282 | Number of People That Can Be Seen in a GridPremium | Medium | Stack, Array, Matrix +1 |
| 2304 | Minimum Path Cost in a Grid | Medium | Array, Dynamic Programming, Matrix |
| 2326 | Spiral Matrix IV | Medium | Array, Linked List, Matrix +1 |
| 2387 | Median of a Row Wise Sorted MatrixPremium | Medium | Array, Binary Search, Matrix |
| 2397 | Maximum Rows Covered by Columns | Medium | Bit Manipulation, Array, Backtracking +2 |
| 2428 | Maximum Sum of an Hourglass | Medium | Array, Matrix, Prefix Sum |
| 2482 | Difference Between Ones and Zeros in Row and Column | Medium | Array, Matrix, Simulation |
| 2510 | Check if There is a Path With Equal Number of 0's And 1'sPremium | Medium | Array, Dynamic Programming, Matrix |
| 2536 | Increment Submatrices by One | Medium | Array, Matrix, Prefix Sum |
| 2545 | Sort the Students by Their Kth Score | Medium | Array, Matrix, Sorting |
| 2556 | Disconnect Path in a Binary Matrix by at Most One Flip | Medium | Depth-First Search, Breadth-First Search, Array +2 |
| 2596 | Check Knight Tour Configuration | Medium | Depth-First Search, Breadth-First Search, Array +2 |
| 2658 | Maximum Number of Fish in a Grid | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 2661 | First Completely Painted Row or Column | Medium | Array, Hash Table, Matrix |
| 2664 | The Knight’s TourPremium | Medium | Array, Backtracking, Matrix |
| 2679 | Sum in a Matrix | Medium | Array, Matrix, Sorting +2 |
| 2684 | Maximum Number of Moves in a Grid | Medium | Array, Dynamic Programming, Matrix |
| 2711 | Difference of Number of Distinct Values on Diagonals | Medium | Array, Hash Table, Matrix |
| 2812 | Find the Safest Path in a Grid | Medium | Breadth-First Search, Union Find, Array +3 |
| 2850 | Minimum Moves to Spread Stones Over Grid | Medium | Breadth-First Search, Array, Dynamic Programming +1 |
| 2852 | Sum of Remoteness of All CellsPremium | Medium | Depth-First Search, Breadth-First Search, Union Find +3 |
| 2906 | Construct Product Matrix | Medium | Array, Matrix, Prefix Sum |
Hard (59)
| # | Problem | Difficulty | Topics |
|---|---|---|---|
| 37 | Sudoku Solver | Hard | Array, Hash Table, Backtracking +1 |
| 85 | Maximal Rectangle | Hard | Stack, Array, Dynamic Programming +2 |
| 174 | Dungeon Game | Hard | Array, Dynamic Programming, Matrix |
| 212 | Word Search II | Hard | Trie, Array, String +2 |
| 329 | Longest Increasing Path in a Matrix | Hard | Depth-First Search, Breadth-First Search, Graph +5 |
| 363 | Max Sum of Rectangle No Larger Than K | Hard | Array, Binary Search, Matrix +2 |
| 407 | Trapping Rain Water II | Hard | Breadth-First Search, Array, Matrix +1 |
| 675 | Cut Off Trees for Golf Event | Hard | Breadth-First Search, Array, Matrix +1 |
| 741 | Cherry Pickup | Hard | Array, Dynamic Programming, Matrix |
| 749 | Contain Virus | Hard | Depth-First Search, Breadth-First Search, Array +2 |
| 778 | Swim in Rising Water | Hard | Depth-First Search, Breadth-First Search, Union Find +4 |
| 296 | Best Meeting PointPremium | Hard | Array, Math, Matrix +1 |
| 302 | Smallest Rectangle Enclosing Black PixelsPremium | Hard | Depth-First Search, Breadth-First Search, Array +2 |
| 317 | Shortest Distance from All BuildingsPremium | Hard | Breadth-First Search, Array, Matrix |
| 499 | The Maze IIIPremium | Hard | Depth-First Search, Breadth-First Search, Graph +5 |
| 568 | Maximum Vacation DaysPremium | Hard | Array, Dynamic Programming, Matrix |
| 631 | Design Excel Sum FormulaPremium | Hard | Graph, Design, Topological Sort +4 |
| 773 | Sliding Puzzle | Hard | Breadth-First Search, Memoization, Array +3 |
| 782 | Transform to Chessboard | Hard | Bit Manipulation, Array, Math +1 |
| 803 | Bricks Falling When Hit | Hard | Union Find, Array, Matrix |
| 827 | Making A Large Island | Hard | Depth-First Search, Breadth-First Search, Union Find +2 |
| 864 | Shortest Path to Get All Keys | Hard | Bit Manipulation, Breadth-First Search, Array +1 |
| 980 | Unique Paths III | Hard | Bit Manipulation, Array, Backtracking +1 |
| 1074 | Number of Submatrices That Sum to Target | Hard | Array, Hash Table, Matrix +1 |
| 1210 | Minimum Moves to Reach Target with Rotations | Hard | Breadth-First Search, Array, Matrix |
| 1263 | Minimum Moves to Move a Box to Their Target Location | Hard | Breadth-First Search, Array, Matrix +1 |
| 1284 | Minimum Number of Flips to Convert Binary Matrix to Zero Matrix | Hard | Bit Manipulation, Breadth-First Search, Array +2 |
| 1289 | Minimum Falling Path Sum II | Hard | Array, Dynamic Programming, Matrix |
| 1293 | Shortest Path in a Grid with Obstacles Elimination | Hard | Breadth-First Search, Array, Matrix |
| 1301 | Number of Paths with Max Score | Hard | Array, Dynamic Programming, Matrix |
| 1349 | Maximum Students Taking Exam | Hard | Bit Manipulation, Array, Dynamic Programming +2 |
| 1368 | Minimum Cost to Make at Least One Valid Path in a Grid | Hard | Breadth-First Search, Graph, Array +3 |
| 1439 | Find the Kth Smallest Sum of a Matrix With Sorted Rows | Hard | Array, Binary Search, Matrix +1 |
| 1444 | Number of Ways of Cutting a Pizza | Hard | Memoization, Array, Dynamic Programming +2 |
| 1463 | Cherry Pickup II | Hard | Array, Dynamic Programming, Matrix |
| 1568 | Minimum Number of Days to Disconnect Island | Hard | Depth-First Search, Breadth-First Search, Array +2 |
| 1591 | Strange Printer II | Hard | Graph, Topological Sort, Array +1 |
| 1595 | Minimum Cost to Connect Two Groups of Points | Hard | Bit Manipulation, Array, Dynamic Programming +2 |
| 1632 | Rank Transform of a Matrix | Hard | Union Find, Graph, Topological Sort +3 |
| 1728 | Cat and Mouse II | Hard | Graph, Topological Sort, Memoization +5 |
| 1970 | Last Day Where You Can Still Cross | Hard | Depth-First Search, Breadth-First Search, Union Find +3 |
| 2088 | Count Fertile Pyramids in a Land | Hard | Array, Dynamic Programming, Matrix |
| 2123 | Minimum Operations to Remove Adjacent Ones in MatrixPremium | Hard | Graph, Array, Matrix |
| 2132 | Stamping the Grid | Hard | Greedy, Array, Matrix +1 |
| 2258 | Escape the Spreading Fire | Hard | Breadth-First Search, Array, Binary Search +1 |
| 2267 | Check if There Is a Valid Parentheses String Path | Hard | Array, Dynamic Programming, Matrix |
| 2290 | Minimum Obstacle Removal to Reach Corner | Hard | Breadth-First Search, Graph, Array +3 |
| 2328 | Number of Increasing Paths in a Grid | Hard | Depth-First Search, Breadth-First Search, Graph +5 |
| 2371 | Minimize Maximum Value in a GridPremium | Hard | Union Find, Graph, Topological Sort +3 |
| 2392 | Build a Matrix With Conditions | Hard | Graph, Topological Sort, Array +1 |
| 2435 | Paths in Matrix Whose Sum Is Divisible by K | Hard | Array, Dynamic Programming, Matrix |
| 2503 | Maximum Number of Points From Grid Queries | Hard | Breadth-First Search, Union Find, Array +4 |
| 2573 | Find the String with LCP | Hard | Greedy, Union Find, Array +3 |
| 2577 | Minimum Time to Visit a Cell In a Grid | Hard | Breadth-First Search, Graph, Array +3 |
| 2617 | Minimum Number of Visited Cells in a Grid | Hard | Stack, Breadth-First Search, Union Find +5 |
| 2713 | Maximum Strictly Increasing Cells in a Matrix | Hard | Memoization, Array, Hash Table +5 |
| 2732 | Find a Good Subset of the Matrix | Hard | Bit Manipulation, Array, Hash Table +1 |
| 2814 | Minimum Time Takes to Reach Destination Without DrowningPremium | Hard | Breadth-First Search, Array, Matrix |
| 2931 | Maximum Spending After Buying Items | Hard | Greedy, Array, Matrix +2 |
Related patterns
Problems sit in more than one pattern more often than not, and the overlap is where the interesting follow-up questions live.
Matrix and Grid pattern FAQ
What is the matrix and grid pattern?
A grid is a graph that nobody bothered to build: each cell is a node and its neighbours are the adjacent cells, so DFS, BFS and union-find all apply unchanged once you write the neighbour loop as a list of offsets rather than four copied blocks.
How many LeetCode problems use the matrix and grid pattern?
This page lists 216 LeetCode problems that the matrix and grid pattern applies to: 32 Easy, 125 Medium and 59 Hard. 178 of them carry a complete Python solution with complexity analysis.
What is the time complexity of the matrix and grid pattern?
O(r · c) time and O(r · c) worst case, O(1) when marking in place space. Flood fill visits every cell at most once across all of its starting points, because a claimed cell is never re-entered — so counting islands is linear in the number of cells even though it launches a traversal from many of them. The space is the stack or queue, which can hold every cell on a grid that is one large region. Overwriting visited cells in the grid itself removes the separate seen structure entirely, at the cost of destroying the input.
When should I use the matrix and grid pattern in an interview?
Cells are connected to their neighbours and you need regions, components or reachability. The shortest path through a grid is wanted, which is BFS with four or eight offsets.
Which matrix and grid problem should I start with?
LeetCode 422. Valid Word Square is the lowest-numbered Easy problem on this page, which makes it the usual starting point: the technique is visible without the problem's own complications getting in the way.
What patterns are related to matrix and grid?
Depth-First Search, Breadth-First Search, Union-Find, Dynamic Programming. Problems frequently sit in more than one of these, and the overlap is where the interesting follow-up questions come from.
More ways in: all 22 patterns, the curated study lists, or the full problem list.
Meet the matrix and grid problem you did not practise
Stealth Interview is a desktop app for macOS and Windows. It reads the coding problem off your screen, returns a working solution with a step-by-step explanation and its time and space complexity, and transcribes what the interviewer is saying — while staying invisible to screen sharing.