Grid Streak Removal and Column Gravity
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Given a rectangular grid of single-digit integers (0 through 9), execute one streak-clearing and gravity pass and return a tuple (runs, collapsed_grid):
- Streak detection (
runs): Locate every maximal straight-line horizontal or vertical streak of at least3matching digits (streaks of0s count just like any other digit). A streak is maximal if it cannot be extended further along its row or column with the same digit. Represent each streak as[start_row, start_col, length], anchored at its leftmost cell for horizontal streaks or its topmost cell for vertical streaks. If a horizontal streak and a vertical streak intersect—or even share the exact same anchor coordinate—include both entries. Returnrunssorted lexicographically (start_rowascending, thenstart_colascending, andlengthascending on ties). - Simultaneous clearing and column gravity (
collapsed_grid): Clear all cells covered by at least one detected streak at the same time (an intersection cell shared by two streaks is cleared once). Within each column independently, drop the remaining uncleared digits straight down to the lowest open slots while keeping their original top-to-bottom order, and pad the vacated upper slots with0. Perform only a single pass—do not re-clear digits that happen to align after falling—and do not mutate the inputgrid.
def detect_runs_and_collapse(
grid: List[List[int]],
) -> Tuple[List[List[int]], List[List[int]]]:
Examples
Example 1
grid = [
[5, 2, 2, 2, 2],
[8, 6, 3, 1, 9],
[4, 6, 7, 8, 3],
[1, 6, 0, 0, 0],
]
Output:
(
[[0, 1, 4], [1, 1, 3], [3, 2, 3]],
[
[5, 0, 0, 0, 0],
[8, 0, 0, 0, 0],
[4, 0, 3, 1, 9],
[1, 0, 7, 8, 3],
],
)
Walk-through: Row 0 has four 2s starting at (0, 1) ([0, 1, 4]), column 1 has three 6s starting at (1, 1) ([1, 1, 3]), and row 3 has three 0s starting at (3, 2) ([3, 2, 3]). Clearing those cells leaves column 0 untouched, wipes column 1 completely to 0s, and drops rows 1 and 2 in columns 2..4 down into rows 2 and 3.
Example 2
grid = [
[9, 3, 3, 3],
[9, 4, 3, 8],
[9, 5, 3, 2],
]
Output:
(
[[0, 0, 3], [0, 1, 3], [0, 2, 3]],
[
[0, 0, 0, 0],
[0, 4, 0, 8],
[0, 5, 0, 2],
],
)
Walk-through: Column 0 forms vertical streak [0, 0, 3], row 0 forms horizontal streak [0, 1, 3], and column 2 forms vertical streak [0, 2, 3], crossing the horizontal streak at (0, 2). Both crossing streaks are reported, (0, 2) is cleared once, and the surviving digits in columns 1 and 3 stay below the newly vacated top cells.
Example 3
grid = [
[4, 4, 7],
[7, 9, 9],
[4, 7, 9],
]
Output:
(
[],
[
[4, 4, 7],
[7, 9, 9],
[4, 7, 9],
],
)
Walk-through: Adjacent pairs of length 2 do not qualify as runs, so runs is empty and the board is returned unchanged.
Example 4
grid = [
[8, 2, 4],
[5, 9, 6],
[5, 1, 3],
[5, 8, 8],
]
Output:
(
[[1, 0, 3]],
[
[0, 2, 4],
[0, 9, 6],
[0, 1, 3],
[8, 8, 8],
],
)
Walk-through: Clearing the vertical streak of three 5s at [1, 0, 3] drops the 8 from (0, 0) to (3, 0). Even though row 3 now reads [8, 8, 8] (and column 0 now starts with three 0s), no cascading pass occurs.
Constraints
0 <= len(grid) <= 3000 <= len(grid[r]) <= 300, and all rows have identical length.- Every entry
grid[r][c]is an integer satisfying0 <= grid[r][c] <= 9. - The input
gridmust not be modified in place.
Step-by-step walkthrough
Understand the two phases and edge rules
Given a rectangular
gridof single-digit integers (0through9),detect_runs_and_collapse(grid)executes a single two-stage board update and returns(runs, collapsed_grid):- Stage 1 — Detect streaks: Locate every maximal horizontal or vertical streak of 3 or more matching adjacent digits. Record each streak as
[start_row, start_col, length], anchored at its leftmost cell (horizontal) or topmost cell (vertical), ordered lexicographically (start_rowascending,start_colascending, andlengthascending on ties). - Stage 2 — Clear and compact: Simultaneously clear every cell covered by any detected streak, slide surviving digits straight down within each column while preserving their top-to-bottom order, and pad vacated upper slots with
0.
Pin down four important rules from the examples before writing code:
- Streaks are maximal: Four
2s in a row ([5, 2, 2, 2, 2]in Example 1) form one streak[0, 1, 4], not two overlapping runs of length 3. 0is a normal digit during detection: Example 1 reports[3, 2, 3]for[0, 0, 0]in row 3;0only acts as empty top padding after gravity finishes.- Horizontal and vertical streaks can cross or share a start cell: In Example 2,
[0, 1, 3]and[0, 2, 3]intersect at(0, 2)— both streaks are reported, and(0, 2)is cleared once. - Single pass only (no cascading): As shown in Example 4, if falling digits line up into three-of-a-kind after dropping (
[8, 8, 8]), they stay untouched.
- Stage 1 — Detect streaks: Locate every maximal horizontal or vertical streak of 3 or more matching adjacent digits. Record each streak as
Why scanning each line once beats starting from every cell
A tempting brute-force approach starts at every cell
(r, c)and walks rightward and downward while digits match. That creates two headaches: - Inside[7, 7, 7, 7, 7], walks starting at columns0,1, and2all have length at least3, so you would falsely report sub-runs[0, 1, 4]and[0, 2, 3]unless you add extra look-behind checks. - Re-walking long lines from every cell takesO(m * n * (m + n))time.Instead, if we scan each row left-to-right once with a single
start_colpointer (and each column top-to-bottom once withstart_row), every streak is automatically maximal and every cell is visited only once per direction (O(m * n)total).Find maximal horizontal runs with a start pointer
Walk across a row keeping
start_colat the beginning of the current streak of equal digits. Whenever columnchits a different digit OR reaches the right edge of the row (c == len(row)), the streak coveringstart_col .. c - 1has just ended, withlength = c - start_col:row = [5, 2, 2, 2, 2] (len = 5) c = 0: start_col = 0 (digit 5) c = 1: row[1] == 2 != 5 -> streak 0..0 ends (length 1 < 3, ignore); start_col = 1 (digit 2) c = 2: row[2] == 2 -> streak continues c = 3: row[3] == 2 -> streak continues c = 4: row[4] == 2 -> streak continues c = 5: c == len(row) -> streak 1..4 ends (length 4 >= 3 -> record [r, 1, 4]!)Notice two clean tricks here: 1. Looping
cup tolen(row)inclusive lets the right edge of the row close the final streak using the exact sameifblock — no copy-pasted cleanup code after the loop! 2. We markremoved[r][col_idx] = Truein a separaterows x colsboolean grid instead of overwritinggridwith0s right away. That waygridstays completely intact when we scan columns next!def add_horizontal_runs( grid: List[List[int]], runs: List[List[int]], removed: List[List[bool]], ) -> None: """Record every maximal horizontal run of length >= 3 and mark its cells.""" for r in range(len(grid)): row = grid[r] start_col = 0 # Step c up to len(row) inclusive so hitting the right edge flushes the final streak. for c in range(1, len(row) + 1): if c == len(row) or row[c] != row[start_col]: length = c - start_col if length >= 3: runs.append([r, start_col, length]) for col_idx in range(start_col, c): removed[r][col_idx] = True start_col = cFind maximal vertical runs the same way
Scanning columns uses the exact same logic with
randcswapped. For each columnc,start_rowmarks the topmost cell of the current vertical streak, and steppingrup torowsflushes streaks that reach the bottom edge. If a vertical run crosses a horizontal run, settingremoved[row_idx][c] = Truea second time is completely harmless:def add_vertical_runs( grid: List[List[int]], runs: List[List[int]], removed: List[List[bool]], ) -> None: """Record every maximal vertical run of length >= 3 and mark its cells.""" rows = len(grid) cols = len(grid[0]) if rows else 0 for c in range(cols): start_row = 0 # Step r up to rows inclusive so hitting the bottom edge flushes the final streak. for r in range(1, rows + 1): if r == rows or grid[r][c] != grid[start_row][c]: length = r - start_row if length >= 3: runs.append([start_row, c, length]) for row_idx in range(start_row, r): removed[row_idx][c] = True start_row = rDrop surviving digits with a bottom-up write pointer
Once
removedmarks every cell to delete, columns do not interact with one another at all. In each columnc, start awrite_rowpointer at the bottom (rows - 1) of a fresh0-filledresultgrid, and scanrupward fromrows - 1down to0:Column values (top to bottom): [9, 8, 3, 3, 3] removed mask: [F, F, T, T, T] (three 3s removed) Scan bottom-up (r = 4 -> 0), starting write_row = 4: r = 4..2: removed is True -> skip r = 1: keep 8 -> result[4][c] = 8, write_row becomes 3 r = 0: keep 9 -> result[3][c] = 9, write_row becomes 2 rows 0..2 were pre-filled -> stay 0! Final column (top to bottom): [0, 0, 0, 9, 8]Scanning bottom-up preserves
9above8in a singleO(rows)pass without shifting elements repeatedly.def apply_gravity( grid: List[List[int]], removed: List[List[bool]], ) -> List[List[int]]: """Drop surviving digits in each column to the bottom and leave 0s at the top.""" rows = len(grid) cols = len(grid[0]) if rows else 0 # Pre-fill with 0 so any top slots left unwritten after compaction stay 0. result = [[0] * cols for _ in range(rows)] for c in range(cols): # write_row points to the lowest still-available slot in column c. write_row = rows - 1 for r in range(rows - 1, -1, -1): if not removed[r][c]: result[write_row][c] = grid[r][c] write_row -= 1 return resultSort the runs and trace Example 1
Python compares lists element-by-element (
start_rowfirst, thenstart_col, thenlength), soruns.sort()orders all horizontal and vertical runs cleanly in one call. Let's trace Example 1 from start to finish:Input grid Marked runs (X = removed) After gravity + top 0s 5 2 2 2 2 5 X X X X 5 0 0 0 0 8 6 3 1 9 --> 8 X 3 1 9 --> 8 0 0 0 0 4 6 7 8 3 4 X 7 8 3 4 0 3 1 9 1 6 0 0 0 1 X X X X 1 0 7 8 3- Horizontal runs:
[0, 1, 4](2 2 2 2in row 0) and[3, 2, 3](0 0 0in row 3). - Vertical runs:
[1, 1, 3](6 6 6in col 1). - Sorted runs:
[[0, 1, 4], [1, 1, 3], [3, 2, 3]]. - Gravity: column
0is untouched ([5, 8, 4, 1]); column1has all four cells cleared ([0, 0, 0, 0]); and in columns2..4, row 0 and row 3 are cleared, so rows 1 and 2 (3,1,9and7,8,3) drop into rows 2 and 3.
- Horizontal runs:
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def add_horizontal_runs( grid: List[List[int]], runs: List[List[int]], removed: List[List[bool]], ) -> None: """Record every maximal horizontal run of length >= 3 and mark its cells.""" for r in range(len(grid)): row = grid[r] start_col = 0 # Step c up to len(row) inclusive so hitting the right edge flushes the final streak. for c in range(1, len(row) + 1): if c == len(row) or row[c] != row[start_col]: length = c - start_col if length >= 3: runs.append([r, start_col, length]) for col_idx in range(start_col, c): removed[r][col_idx] = True start_col = c def add_vertical_runs( grid: List[List[int]], runs: List[List[int]], removed: List[List[bool]], ) -> None: """Record every maximal vertical run of length >= 3 and mark its cells.""" rows = len(grid) cols = len(grid[0]) if rows else 0 for c in range(cols): start_row = 0 # Step r up to rows inclusive so hitting the bottom edge flushes the final streak. for r in range(1, rows + 1): if r == rows or grid[r][c] != grid[start_row][c]: length = r - start_row if length >= 3: runs.append([start_row, c, length]) for row_idx in range(start_row, r): removed[row_idx][c] = True start_row = r def apply_gravity( grid: List[List[int]], removed: List[List[bool]], ) -> List[List[int]]: """Drop surviving digits in each column to the bottom and leave 0s at the top.""" rows = len(grid) cols = len(grid[0]) if rows else 0 # Pre-fill with 0 so any top slots left unwritten after compaction stay 0. result = [[0] * cols for _ in range(rows)] for c in range(cols): # write_row points to the lowest still-available slot in column c. write_row = rows - 1 for r in range(rows - 1, -1, -1): if not removed[r][c]: result[write_row][c] = grid[r][c] write_row -= 1 return result def detect_runs_and_collapse( grid: List[List[int]], ) -> Tuple[List[List[int]], List[List[int]]]: rows = len(grid) cols = len(grid[0]) if rows else 0 # runs: list of [start_row, start_col, length] for every maximal run of >= 3 equal digits. runs: List[List[int]] = [] # removed: rows x cols boolean mask; separates detection from deletion so crossing runs # both see the original grid and shared intersection cells are removed once. removed: List[List[bool]] = [[False] * cols for _ in range(rows)] add_horizontal_runs(grid, runs, removed) add_vertical_runs(grid, runs, removed) # Python sorts 3-element lists by row ascending, then col ascending (and length on ties). runs.sort() collapsed_grid = apply_gravity(grid, removed) return runs, collapsed_grid✅ Submit now — all tests should pass.
Intuition & how it works
Picture a single turn on a tile-matching game board (without chain reactions): first, we lay a transparent plastic sheet over the board and draw checkmarks over every horizontal or vertical maximal run (the longest unbroken streak of identical adjacent digits that cannot extend further) of length 3 or more; second, we lift out all checkmarked tiles at once and let the remaining tiles in each column slide straight down to the floor while filling the empty top slots with 0. That transparent sheet is our boolean mask (removed, a parallel True/False grid of the same size that records which cells will disappear without modifying the original numbers yet).
Mutating the grid directly during the horizontal scan fails immediately whenever a horizontal run and a vertical run cross, because overwriting the horizontal streak with 0s erases the shared intersection digit before the vertical scan ever sees it! Checking fixed sliding windows of size 3 also fails on stage 1 because [5, 2, 2, 2, 2] would be reported as two overlapping length-3 runs instead of a single run [0, 1, 4], while simulating gravity one square at a time in a while loop wastes quadratic time per column instead of packing surviving tiles in one bottom-up pass.
Let's trace Example 2 — [[9, 3, 3, 3], [9, 4, 3, 8], [9, 5, 3, 2]] — step by step:
- Horizontal scan: row
0is[9, 3, 3, 3]. Using a sentinel boundary step (loopingcone index past the end of the row soc == 4flushes the streak automatically), we record[0, 1, 3]and mark(0, 1),(0, 2), and(0, 3)asTrueinremovedwhile leavinggriduntouched. - Vertical scan: column
0reads[9, 9, 9]([0, 0, 3]), and column2still reads[3, 3, 3]fromgrid, so we record[0, 2, 3]and mark(0, 2),(1, 2), and(2, 2)inremoved(marking(0, 2)Truea second time safely). - Sort & collapse: sorting the collected streaks in lexicographical order (comparing element
0first, then element1, then element2on ties) gives[[0, 0, 3], [0, 1, 3], [0, 2, 3]]. Then two-pointer compaction (scanning bottom-up with awrite_rowpointer in each column) keeps4, 5at the bottom of column1and8, 2at the bottom of column3, producing[[0, 0, 0, 0], [0, 4, 0, 8], [0, 5, 0, 2]].
Complexity
Let m be the number of rows, n be the number of columns, and R be the number of detected runs.
- Time:
O(m * n + R log R). The horizontal scan visits every cell once (O(m * n)), markingremovedtouches each cell at most once per direction (O(m * n)), the vertical scan visits every cell once (O(m * n)), and bottom-up gravity visits every cell once (O(m * n)). Sorting theRruns takesO(R log R), whereR <= 2 * m * n / 3because horizontal runs are disjoint and each contains at least3cells (and likewise for vertical runs). - Space:
O(m * n)to allocate them x nbooleanremovedmask and them x noutput grid (leaving the caller's inputgridunmodified), plusO(R)for therunsoutput list.
Edge cases
- Empty grids (
[]or[[]]): guarded bycols = len(grid[0]) if rows else 0, returning([], [])or([], [[]])cleanly without anIndexError. - Boards narrower or shorter than 3 cells: streaks have length at most
1or2, so zero runs are recorded in that direction and all digits stay in place. - Runs of
4or more identical digits:[5, 2, 2, 2, 2]in Example 1 closes only atc == 5, emitting a single maximal run[0, 1, 4]. - Runs of
0s in the initial grid:0is treated like any digit0–9during detection (for example[3, 2, 3]in Example 1);0only means "empty top padding" after gravity runs. - Crossing (
+orTorL) runs and shared start cells: both the horizontal and vertical runs are recorded (even when both start at(0, 0), such as[[0, 0, 3], [0, 0, 4]]), and their shared cell is deleted once. - Digits lining up after falling: as shown in Example 4, compaction executes once; newly aligned triples formed after gravity (
[8, 8, 8]) are not re-collapsed.
Common mistakes
- Mutating
gridwhile scanning horizontally: overwriting horizontal runs with0s beforeadd_vertical_runsruns breaks vertical runs that cross them (and could even create fake vertical runs of0s!). - Reporting sliding windows of 3 instead of maximal runs: checking
grid[r][c] == grid[r][c+1] == grid[r][c+2]works for marking deleted cells, but fails detection by splitting a length-4 or length-5 run into multiple length-3 entries. - Forgetting to flush a run that reaches the right or bottom wall: stopping the loop at
len(row) - 1without a post-loop check silently drops every run that touches the last column or last row. - Flipping surviving column order during gravity: collecting surviving digits bottom-up into a list and writing them top-down reverses the column upside down; walking both
randwrite_rowbottom-up preserves exact order. - Looping until no runs remain (cascading): repeating detect-and-collapse not only contradicts the single-operation specification, it loops forever because the
0s dropped in at the top form runs of three0s on the very next pass!
Alternative approaches
O(m * n)run collection withoutruns.sort(): precomputeright_len[r][c](how many equal digits extend right from(r, c)) via a right-to-left DP pass anddown_len[r][c]via a bottom-to-top DP pass, then iterate(r, c)in row-major order (r = 0..m-1,c = 0..n-1) and emit streaks anchored at(r, c)(emitting the shorter one first if both horizontal and vertical streaks start at(r, c)). Because(r, c)is visited in exact(row, col)order,runsis already sorted without calling.sort().- In-place gravity (if mutating input is allowed): if an interviewer explicitly asks for
O(1)auxiliary grid space (for instance, negating values ingridto mark removals when digits are positive1..9), the bottom-upwrite_rowloop can write directly back intogrid[write_row][c]and zero out0 .. write_rowafterward becausewrite_row >= ralways holds.
Follow-up questions
- How would you adapt the simulation if newly aligned triples after gravity had to keep collapsing until the board stabilized? Wrap detect-and-collapse in a
while True:loop that stops as soon asrunsis empty, and change the empty-cell filler from0to a dedicated sentinel such asNoneor-1that run detection ignores — otherwise three newly added0s at the top would trigger an infinite loop of0-runs! Because every cascading round deletes at least3real tiles out ofm * n, at most(m * n) // 3rounds can happen, givingO((m * n)^2)worst-case time. - What changes if diagonal and anti-diagonal streaks of length 3 or more also count as valid runs? Add two more line-scan helpers using the exact same
startpointer pattern: one walking down-right ((r + k, c + k)) from every top-row and left-column border cell, and one walking down-left ((r + k, c - k)) from every top-row and right-column border cell, defining each run's start cell as its topmost cell. Each cell belongs to exactly one main diagonal and one anti-diagonal, so detection still runs inO(m * n)time and marks the same sharedremovedmask. - Suppose clearing tiles awards 10 points per unique cleared cell plus a 50-point bonus for each run of length at least 4—how would you calculate the score? Compute tile points by counting
Trueentries inremoved(10 * sum(sum(row) for row in removed)) rather than summingrun[2]acrossruns, because summing run lengths would double-count intersection cells where horizontal and vertical runs cross! Then add50for each[r, c, length]inrunswithlength >= 4— both numbers are ready right after detection with zero extra passes.
Follow-up questions
- How would you adapt the simulation if newly aligned triples after gravity had to keep collapsing until the board stabilized?
- What changes if diagonal and anti-diagonal streaks of length 3 or more also count as valid runs?
- Suppose clearing tiles awards 10 points per unique cleared cell plus a 50-point bonus for each run of length at least 4—how would you calculate the score?
Similar questions
- Valid Hat Pairings and Maximum Score
- Centered Span Availability Queries Over Dynamic Reservations
- Robot Trajectory Boundedness with Obstacles
- Grid Robot Return to Origin
- Per-Client Sliding Window Hit Counter
- Largest Digit-Sum Group Across an Integer Range
More Roblox interview questions
- Detect Grid Streaks and Collapse Columns Medium
- Furthest Unblocked Cardinal Walk Around Grid Beams Medium
- Dual-Key Sliding Window Request Throttler Medium Pro
- Profit-Optimal Three-Stage Bakery Line Medium Pro
- Bayesian Posterior and Marginal Evidence Hard Pro
- Per-Group Top-k Semantics: ROW_NUMBER, RANK, and DENSE_RANK Medium Pro
- Difference-in-Differences Effect and Pretrend Check Hard Pro
- Total Sample Size Calculator for Two-Arm Z-Tests Hard Pro
- Per-Arm Power Sizing and Bayesian Posterior Updating Hard Pro
- Valid Hat Pairings and Maximum Score Hard Pro