Skip to contentKEEP THE CRAFTTHE SANCTUARY

Matrix / Grid

Represent a rectangular grid with independent Python row lists, then reason about cell coordinates, orthogonal neighbors, and discovery state. Separate row ownership from traversal so one update or visit cannot silently affect another cell.

2 practice exercises15 interview problems

Recognize it when The input has row and column positions with bounded neighbor moves.

Checking your account…

Matrix / Grid Code Labs

Mental Model

A Python matrix is a list of row lists. Coordinates are ordered pairs (row, column), and the two bounds are independent. A rectangular grid has a common column count; a ragged list requires a different bound for each row and must be named as such in the contract.

Coordinates and Rectangular Shape

Read grid[row][column]: first select a row, then a cell. For a nonempty rectangular grid, cache rows = len(grid) and columns = len(grid[0]). Guard the empty grid before reading row zero. A four-direction neighbor changes exactly one coordinate by one.

Allocate Independent Rows

[[0] * columns] * rows repeats references to the same inner list. Updating one cell then changes the corresponding column in every aliased row. A comprehension evaluates the row expression once per iteration and creates independent row objects.

Allocate Independent Grid Rows

Reference
def make_grid(rows, columns, value):
    return [[value for _ in range(columns)] for _ in range(rows)]
Practice

Implement make_grid(rows, columns, value). For non-negative dimensions, return distinct row lists so replacing one cell cannot change another row. The initializer value itself is shared by reference; mutating a mutable initializer is not a deep-copy operation.

Public tests

  • Verify rows do not alias

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Allocate Independent Grid Rows

def make_grid(rows, columns, value):
    return [[value for _ in range(columns)] for _ in range(rows)]

The Python list documentation(opens in a new tab) defines shallow copying: copying the outer list alone does not clone nested rows.

Traverse Grid Neighbors

Treat a grid as an implicit graph when movement rules define edges. Scan cells in row-major order; when an active cell is not visited, start a DFS or BFS and mark neighbors when discovered. Each cell enters one component traversal at most once, so the total work is O(rows × columns), not the number of starts multiplied by grid size.

Visit Each Grid Component

Reference
def grid_component_sizes(grid):
    if not grid:
        return []
    rows, columns = len(grid), len(grid[0])
    visited = set()
    sizes = []
    for row in range(rows):
        for column in range(columns):
            if grid[row][column] != 1 or (row, column) in visited:
                continue
            stack = [(row, column)]
            visited.add((row, column))
            size = 0
            while stack:
                current_row, current_column = stack.pop()
                size += 1
                for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                    neighbor = (current_row + dr, current_column + dc)
                    if 0 <= neighbor[0] < rows and 0 <= neighbor[1] < columns and grid[neighbor[0]][neighbor[1]] == 1 and neighbor not in visited:
                        visited.add(neighbor)
                        stack.append(neighbor)
            sizes.append(size)
    return sizes
Practice

Implement grid_component_sizes(grid). Return four-direction 1-component sizes in row-major discovery order without mutating the grid. The grid is rectangular with consistent row widths, possibly empty.

Public tests

  • Verify four-direction components

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Visit Each Grid Component

def grid_component_sizes(grid):
    if not grid:
        return []
    rows, columns = len(grid), len(grid[0])
    visited = set()
    sizes = []
    for row in range(rows):
        for column in range(columns):
            if grid[row][column] != 1 or (row, column) in visited:
                continue
            stack = [(row, column)]
            visited.add((row, column))
            size = 0
            while stack:
                current_row, current_column = stack.pop()
                size += 1
                for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                    neighbor = (current_row + dr, current_column + dc)
                    if 0 <= neighbor[0] < rows and 0 <= neighbor[1] < columns and grid[neighbor[0]][neighbor[1]] == 1 and neighbor not in visited:
                        visited.add(neighbor)
                        stack.append(neighbor)
            sizes.append(size)
    return sizes

Trace Discovery Before Processing

Use the adjacent component Lab with two rows and three columns. The first region grows downward; the isolated upper-right cell becomes a second region. A coordinate enters visited before its later pop, which prevents duplicate pending work.

print(grid_component_sizes([[1, 0, 1], [1, 0, 0]])) followed by print(grid_component_sizes([]))

Step Executed statement State Why
1 rows, columns = len(grid), len(grid[0]); visited = set(); sizes = [] rows = 2; columns = 3; sizes = [] Each dimension gets its own bound; the rectangular shape is the Lab precondition.
2 stack = [(row, column)]; visited.add((row, column)); size = 0 stack = [(0, 0)]; visited = {(0, 0)}; size = 0 The first active start is discovered before processing.
3 current_row, current_column = stack.pop(); size += 1 current = (0, 0); size = 1; stack = [] Only a removed frontier cell contributes to the region size.
4 visited.add(neighbor); stack.append(neighbor) neighbor = (1, 0); stack = [(1, 0)]; visited = {(0, 0), (1, 0)} The downward active neighbor is marked now; later scans cannot enqueue it again.
5 current_row, current_column = stack.pop(); size += 1; sizes.append(size) after processing (1, 0): size = 2; sizes = [2] Its only active neighbor is already visited, so the first stack empties.
6 stack = [(row, column)]; visited.add((row, column)); size = 0; current_row, current_column = stack.pop(); size += 1; sizes.append(size) start = (0, 2); final sizes = [2, 1] The outer scan finds the isolated cell next; the lower-left start is skipped as visited.
Print Output
1 [2, 1]
2 []

The outer scan fixes the order of component results, while the stack only controls processing within a component. Bounds preserve rectangular coordinates, and discovery-time marking makes the work proportional to the number of cells.

Choose Matrix or Sparse Coordinates

Use a matrix when most positions exist and direct coordinate lookup matters. Use a set or dictionary of coordinates for a huge sparse plane, especially when only a small fraction of cells are active. Use an adjacency list when neighbors are arbitrary rather than derived from local coordinate moves.

Grid Coordinates and Row Ownership Mistakes

  • Swapping row and column bounds works on square examples and fails on rectangular grids.
  • Marking a cell only when removed from the frontier allows duplicate enqueues.
  • Mutating the input as visited state may violate the function’s ownership contract.
  • Copying only the outer list preserves row alias relationships.
  • Recursive flood fill can exceed Python’s recursion limit on a long component.

Explain It in an Interview

State the coordinate convention and whether diagonal movement exists. Define when a cell becomes visited and what the frontier contains. Explain O(rows × columns) by charging constant neighbor work to each cell once, and distinguish auxiliary frontier/visited space from any required output.

Visit Each Grid Component(opens in a new tab) isolates traversal mechanics. Number of Islands(opens in a new tab) requires recognizing the same implicit graph inside a larger prompt.

Python Version Note

Python 3.11+

The examples use standard Python containers and syntax available in the supported browser runtime; Matrix / Grid itself is taught as an interview abstraction.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Read or replace a cellO(1)O(1)Valid row and column positions in a rectangular list of lists.
Allocate or traverse all cellsO(r * c)O(r * c)r rows and c columns; four neighbors per cell. Traversal includes visited/frontier storage.

Space

O(1) for read or replace a cell; O(r * c) for allocate or traverse all cells.

Assumptions

  • Valid row and column positions in a rectangular list of lists.
  • r rows and c columns; four neighbors per cell. Traversal includes visited/frontier storage.

Invariants Worth Saying Aloud

  1. Every coordinate is checked against its own dimension: row against rows, column against columns.
  2. Distinct row lists prevent an assignment in one row from changing another row.
  3. Mark a cell visited when adding it to the frontier so each active cell is processed once.

When To Use Or Avoid Matrix / Grid

Use It When

  • Use independent row lists for dense rectangular input and cell updates.
  • Use a visited coordinate set when traversal must preserve the input.
  • Treat the grid as an implicit graph when neighbors follow local coordinate rules.

Choose Another Tool When

  • Prefer a coordinate set or dictionary when most positions are absent.
  • Use an adjacency list when connections do not follow grid geometry.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Allocating several references to one row

Repeating one inner list shares the same row object. Changing one cell then changes every displayed row at that column.

Prevent it: Create a fresh row list for each row. This guarantees row independence; it does not deep-copy a mutable initializer stored inside each cell.

Avoid

grid = [[0] * columns] * rows
grid[0][1] = 7

Use instead

grid = [[0] * columns for _ in range(rows)]
grid[0][1] = 7

Checking a column against the row count

A square example hides swapped dimensions. Column 2 is valid in a two-row, three-column grid, but a row-count bound incorrectly rejects it.

Prevent it: Name rows and columns separately and test a rectangular example before traversal.

Avoid

inside = 0 <= row < rows and 0 <= column < rows

Use instead

inside = 0 <= row < rows and 0 <= column < columns

Changing four-direction connectivity into eight directions

Adding diagonal moves silently merges cells that the Lab treats as separate components. Connectivity belongs to the problem contract.

Prevent it: List the allowed offsets explicitly and test two diagonally touching cells.

Avoid

offsets = [(dr, dc) for dr in (-1, 0, 1) for dc in (-1, 0, 1) if (dr, dc) != (0, 0)]

Use instead

offsets = [(1, 0), (-1, 0), (0, 1), (0, -1)]

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.