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):

  1. Streak detection (runs): Locate every maximal straight-line horizontal or vertical streak of at least 3 matching digits (streaks of 0s 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. Return runs sorted lexicographically (start_row ascending, then start_col ascending, and length ascending on ties).
  2. 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 with 0. Perform only a single pass—do not re-clear digits that happen to align after falling—and do not mutate the input grid.
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) <= 300
  • 0 <= len(grid[r]) <= 300, and all rows have identical length.
  • Every entry grid[r][c] is an integer satisfying 0 <= grid[r][c] <= 9.
  • The input grid must not be modified in place.

Step-by-step walkthrough

  1. Understand the two phases and edge rules

    Given a rectangular grid of single-digit integers (0 through 9), detect_runs_and_collapse(grid) executes a single two-stage board update and returns (runs, collapsed_grid):

    1. 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_row ascending, start_col ascending, and length ascending on ties).
    2. 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.
    • 0 is a normal digit during detection: Example 1 reports [3, 2, 3] for [0, 0, 0] in row 3; 0 only 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.
  2. 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 columns 0, 1, and 2 all have length at least 3, 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 takes O(m * n * (m + n)) time.

    Instead, if we scan each row left-to-right once with a single start_col pointer (and each column top-to-bottom once with start_row), every streak is automatically maximal and every cell is visited only once per direction (O(m * n) total).

  3. Find maximal horizontal runs with a start pointer

    Walk across a row keeping start_col at the beginning of the current streak of equal digits. Whenever column c hits a different digit OR reaches the right edge of the row (c == len(row)), the streak covering start_col .. c - 1 has just ended, with length = 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 c up to len(row) inclusive lets the right edge of the row close the final streak using the exact same if block — no copy-pasted cleanup code after the loop! 2. We mark removed[r][col_idx] = True in a separate rows x cols boolean grid instead of overwriting grid with 0s right away. That way grid stays 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 = c
    
  4. Find maximal vertical runs the same way

    Scanning columns uses the exact same logic with r and c swapped. For each column c, start_row marks the topmost cell of the current vertical streak, and stepping r up to rows flushes streaks that reach the bottom edge. If a vertical run crosses a horizontal run, setting removed[row_idx][c] = True a 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 = r
    
  5. Drop surviving digits with a bottom-up write pointer

    Once removed marks every cell to delete, columns do not interact with one another at all. In each column c, start a write_row pointer at the bottom (rows - 1) of a fresh 0-filled result grid, and scan r upward from rows - 1 down to 0:

    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 9 above 8 in a single O(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 result
    
  6. Sort the runs and trace Example 1

    Python compares lists element-by-element (start_row first, then start_col, then length), so runs.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 2 in row 0) and [3, 2, 3] (0 0 0 in row 3).
    • Vertical runs: [1, 1, 3] (6 6 6 in col 1).
    • Sorted runs: [[0, 1, 4], [1, 1, 3], [3, 2, 3]].
    • Gravity: column 0 is untouched ([5, 8, 4, 1]); column 1 has all four cells cleared ([0, 0, 0, 0]); and in columns 2..4, row 0 and row 3 are cleared, so rows 1 and 2 (3,1,9 and 7,8,3) drop into rows 2 and 3.
  7. 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 0 is [9, 3, 3, 3]. Using a sentinel boundary step (looping c one index past the end of the row so c == 4 flushes the streak automatically), we record [0, 1, 3] and mark (0, 1), (0, 2), and (0, 3) as True in removed while leaving grid untouched.
  • Vertical scan: column 0 reads [9, 9, 9] ([0, 0, 3]), and column 2 still reads [3, 3, 3] from grid, so we record [0, 2, 3] and mark (0, 2), (1, 2), and (2, 2) in removed (marking (0, 2) True a second time safely).
  • Sort & collapse: sorting the collected streaks in lexicographical order (comparing element 0 first, then element 1, then element 2 on ties) gives [[0, 0, 3], [0, 1, 3], [0, 2, 3]]. Then two-pointer compaction (scanning bottom-up with a write_row pointer in each column) keeps 4, 5 at the bottom of column 1 and 8, 2 at the bottom of column 3, 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)), marking removed touches 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 the R runs takes O(R log R), where R <= 2 * m * n / 3 because horizontal runs are disjoint and each contains at least 3 cells (and likewise for vertical runs).
  • Space: O(m * n) to allocate the m x n boolean removed mask and the m x n output grid (leaving the caller's input grid unmodified), plus O(R) for the runs output list.

Edge cases

  • Empty grids ([] or [[]]): guarded by cols = len(grid[0]) if rows else 0, returning ([], []) or ([], [[]]) cleanly without an IndexError.
  • Boards narrower or shorter than 3 cells: streaks have length at most 1 or 2, so zero runs are recorded in that direction and all digits stay in place.
  • Runs of 4 or more identical digits: [5, 2, 2, 2, 2] in Example 1 closes only at c == 5, emitting a single maximal run [0, 1, 4].
  • Runs of 0s in the initial grid: 0 is treated like any digit 0–9 during detection (for example [3, 2, 3] in Example 1); 0 only means "empty top padding" after gravity runs.
  • Crossing (+ or T or L) 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 grid while scanning horizontally: overwriting horizontal runs with 0s before add_vertical_runs runs breaks vertical runs that cross them (and could even create fake vertical runs of 0s!).
  • 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) - 1 without 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 r and write_row bottom-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 three 0s on the very next pass!

Alternative approaches

  • O(m * n) run collection without runs.sort(): precompute right_len[r][c] (how many equal digits extend right from (r, c)) via a right-to-left DP pass and down_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, runs is 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 in grid to mark removals when digits are positive 1..9), the bottom-up write_row loop can write directly back into grid[write_row][c] and zero out 0 .. write_row afterward because write_row >= r always 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 as runs is empty, and change the empty-cell filler from 0 to a dedicated sentinel such as None or -1 that run detection ignores — otherwise three newly added 0s at the top would trigger an infinite loop of 0-runs! Because every cascading round deletes at least 3 real tiles out of m * n, at most (m * n) // 3 rounds can happen, giving O((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 start pointer 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 in O(m * n) time and marks the same shared removed mask.
  • 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 True entries in removed (10 * sum(sum(row) for row in removed)) rather than summing run[2] across runs, because summing run lengths would double-count intersection cells where horizontal and vertical runs cross! Then add 50 for each [r, c, length] in runs with length >= 4 — both numbers are ready right after detection with zero extra passes.

Follow-up questions

Similar questions

More Roblox interview questions

All 84 Roblox questions →