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)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…
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.
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.
[[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.
def make_grid(rows, columns, value):
return [[value for _ in range(columns)] for _ in range(rows)]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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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.
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.
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 sizesImplement 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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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 sizesUse 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. |
| 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.
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.
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 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)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Read or replace a cell | O(1) | O(1) | Valid row and column positions in a rectangular list of lists. |
| Allocate or traverse all cells | O(r * c) | O(r * c) | r rows and c columns; four neighbors per cell. Traversal includes visited/frontier storage. |
O(1) for read or replace a cell; O(r * c) for allocate or traverse all cells.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
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.
grid = [[0] * columns] * rows
grid[0][1] = 7grid = [[0] * columns for _ in range(rows)]
grid[0][1] = 7Where you will hit this: Visit Each Grid Component(opens in a new tab)
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.
inside = 0 <= row < rows and 0 <= column < rowsinside = 0 <= row < rows and 0 <= column < columnsWhere you will hit this: Visit Each Grid Component(opens in a new tab)
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.
offsets = [(dr, dc) for dr in (-1, 0, 1) for dc in (-1, 0, 1) if (dr, dc) != (0, 0)]offsets = [(1, 0), (-1, 0), (0, 1), (0, -1)]Where you will hit this: Number of Islands(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27