Detect Grid Streaks and Collapse Columns

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given a rectangular m x n matrix grid of positive integers, simulate a single scoring-and-gravity pass on a tile board by returning (matches, result):

def match_three(grid: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]:

A match is a maximal contiguous streak of 3 or more identical numbers along a single row (horizontal) or along a single column (vertical):

  • Maximal streaks only: A streak of k >= 3 identical adjacent numbers counts as one entry [value, k], never as multiple shorter overlapping streaks. Two streaks of the same number separated by at least one different number in the same row or column count as separate entries.
  • Required scan order for matches: Record every horizontal match before any vertical match.
    1. Scan rows from top (r = 0) to bottom (r = m - 1), and within each row scan left (c = 0) to right (c = n - 1), ordering horizontal streaks by their leftmost cell.
    2. Scan columns from left (c = 0) to right (c = n - 1), and within each column scan top (r = 0) to bottom (r = m - 1), ordering vertical streaks by their topmost cell.
  • Shared intersections: Both scans inspect the unmodified input board. If a cell belongs to a horizontal streak and a vertical streak simultaneously, include both streaks in matches.
  • Single clear-and-collapse pass: After collecting all matches, turn every cell that participated in at least one match into 0. Then, in each column independently, slide all remaining positive integers down to the bottommost rows while keeping their original top-to-bottom relative order, leaving 0 in any vacated cells at the top of the column.
  • No chain reactions: Perform detection, clearing, and column gravity once; if falling tiles happen to form new streaks of length 3 or more in result, leave them untouched. When no matches exist, return ([], result) where result equals grid.

Examples

Example 1

Input:  grid = [[4, 8, 2, 9],
                [4, 3, 6, 9],
                [4, 4, 4, 4],
                [7, 8, 5, 9]]
Output: ([[4, 4], [4, 3]],
         [[0, 0, 0, 0],
          [0, 8, 2, 9],
          [0, 3, 6, 9],
          [7, 8, 5, 9]])
  • Row 2 contains four consecutive 4s, producing the horizontal match [4, 4].
  • Column 0 contains three consecutive 4s in rows 0..2, producing the vertical match [4, 3] (listed after the horizontal match even though it starts at row 0, and sharing cell (2, 0)).
  • Column 3 holds [9, 9, 4, 9]: the 4 breaks the 9s into lengths 2 and 1, so no match occurs there during detection.
  • Clearing row 2 and rows 0..2 of column 0 leaves 7 at the bottom of column 0, while columns 1, 2, and 3 each drop their top two cells down by one row. Even though column 3 now ends with three 9s ([0, 9, 9, 9]), gravity stops after one pass.

Example 2

Input:  grid = [[5, 9, 2, 6],
                [3, 9, 9, 9],
                [8, 9, 4, 1]]
Output: ([[9, 3], [9, 3]],
         [[5, 0, 0, 0],
          [3, 0, 2, 6],
          [8, 0, 4, 1]])

Row 1 (columns 1..3) and column 1 (rows 0..2) each form a streak of three 9s intersecting at (1, 1). Both [9, 3] streaks are recorded. Clearing those five cells empties column 1 completely and drops 2 and 6 from row 0 into row 1.

Example 3

Input:  grid = [[6, 6, 6, 1, 6, 6, 6, 6],
                [2, 5, 2, 9, 3, 4, 3, 8]]
Output: ([[6, 3], [6, 4]],
         [[0, 0, 0, 1, 0, 0, 0, 0],
          [2, 5, 2, 9, 3, 4, 3, 8]])

In row 0, the 1 at column 3 separates a length-3 streak of 6s from a length-4 streak of 6s, yielding [[6, 3], [6, 4]]. Because all cleared cells are already in row 0, no positive values sit above them to fall.

Constraints

  • 1 <= m, n <= 100, where m = len(grid) and every row has length n
  • 1 <= grid[r][c] <= 10^9

Step-by-step walkthrough

  1. Understand the problem and the two key traps

    We are given an m x n grid of positive integers and must simulate one single pass of streak detection and column gravity (without subsequent chain reactions), returning (matches, result):

    1. matches: a list of [value, length] pairs for every maximal run (the longest unbroken streak of equal adjacent numbers) of length 3 or more — all horizontal matches first (rows top to bottom, left to right), followed by all vertical matches (columns left to right, top to bottom).
    2. result: the grid after replacing every matched cell with 0 and letting surviving numbers in each column slide down to the bottom in their original vertical order.

    Two subtle rules dictate the structure of our code:

    • Maximal runs, not 3-cell windows: [4, 4, 4, 4] is one match [4, 4], not two overlapping triples [4, 3].
    • Mark everything before clearing anything: a cell can belong to both a horizontal match and a vertical match at the same time. If we overwrote row matches with 0 immediately, the vertical scan would see a 0 at the intersection and miss the column match!
    Input board (Example 2)   Wrong (zero row 1 early)     Right (mark in a mask first)
      5  9  2  6                5  9  2  6                   .  T  .  .
      3  9  9  9     --->       3  0  0  0  (col 1 broken!)  .  T  T  T   row 1 -> [9, 3]
      8  9  4  1                8  9  4  1                   .  T  .  .   col 1 -> [9, 3]
    

    So we split the algorithm into two clean phases: scan and mark on the untouched input grid using a True/False mask matched, then clear and drop into a fresh result grid.

  2. Find maximal runs in one line with two pointers

    Whether we are scanning a row from left to right or a column from top to bottom, the task is identical: partition a 1D list line into maximal contiguous streaks of equal numbers, and keep the streaks whose length is at least 3.

    We use two indices, start and end:

    • start sits on the first element of the current streak.
    • end advances rightward as long as line[end] == line[start].
    • When end stops (either at a different value or at len(line)), end - start is the full streak length.
    • Setting start = end jumps straight to the next distinct streak, so no streak is ever split or counted twice, and every element is visited once.
    line = [6, 6, 6, 1, 6, 6, 6, 6]   (Row 0 of Example 3)
    index:  0  1  2  3  4  5  6  7
    
    Pass 1: start = 0, end walks to 3 -> run_length = 3 - 0 = 3 >= 3 -> record (0, 3)
    Pass 2: start = 3, end walks to 4 -> run_length = 4 - 3 = 1 <  3 -> skip
    Pass 3: start = 4, end walks to 8 -> run_length = 8 - 4 = 4 >= 3 -> record (4, 4)
    Pass 4: start = 8 == len(line) -> done!
    
    def find_runs(line: List[int]) -> List[Tuple[int, int]]:
        """Return (start_index, run_length) for every maximal run of >= 3 equal values."""
        # runs: list of (start_index, run_length) pairs in left-to-right order
        runs = []
        start = 0
    
        # Two-pointer group scan: `start` anchors a streak, `end` walks until the value changes.
        while start < len(line):
            end = start
            while end < len(line) and line[end] == line[start]:
                end += 1
    
            run_length = end - start
            if run_length >= 3:
                runs.append((start, run_length))
    
            # Jump `start` straight to `end` so every streak is maximal and never split or double-counted.
            start = end
    
        return runs
    
  3. Scan rows first, then columns, into a boolean mask

    Now we apply find_runs to every row and then every column:

    1. Horizontal pass: loop r from 0 to rows - 1. Each row grid[r] is already a list, so find_runs(grid[r]) finds horizontal matches left to right. Append [grid[r][start], run_length] to matches and mark matched[r][c] = True for every cell in that run.
    2. Vertical pass: loop c from 0 to cols - 1. Extract column c top to bottom into a temporary list column, run find_runs(column), append [column[start], run_length] to matches, and mark matched[r][c] = True for every cell in that run.

    Running all rows before all columns produces the exact output order required by the statement. And if a cell belongs to both a row match and a column match, both runs append to matches, while setting matched[r][c] = True a second time harmlessly leaves it True.

        rows = len(grid)
        cols = len(grid[0])
    
        # matches: list of [tile_value, run_length], e.g. [[4, 4], [4, 3]]
        matches = []
        # matched: rows x cols boolean mask; matched[r][c] is True when (r, c) is in >= 1 match.
        matched = [[False] * cols for _ in range(rows)]
    
        # Phase 1a — Horizontal matches: scan rows top to bottom, each row left to right.
        for r in range(rows):
            for start, run_length in find_runs(grid[r]):
                matches.append([grid[r][start], run_length])
                for c in range(start, start + run_length):
                    matched[r][c] = True
    
        # Phase 1b — Vertical matches: scan columns left to right, each column top to bottom.
        for c in range(cols):
            column = []
            for r in range(rows):
                column.append(grid[r][c])
            for start, run_length in find_runs(column):
                matches.append([column[start], run_length])
                for r in range(start, start + run_length):
                    matched[r][c] = True
    
  4. Simulate gravity per column with a bottom-up write pointer

    Columns do not interact during gravity — numbers only fall straight down inside their own column.

    Create a fresh rows x cols grid result initialized to all 0s. For each column c, place a write_row pointer at the bottom (rows - 1) and walk a read row r from the bottom (rows - 1) up to 0:

    • If matched[r][c] is True, skip it — that cell was cleared.
    • If matched[r][c] is False, copy grid[r][c] into result[write_row][c] and move write_row up by 1.

    Why scan from the bottom up instead of the top down? Because the lowest surviving tile lands on the bottom row (rows - 1), the second-lowest lands on rows - 2, and so on, preserving their original vertical order. Any slots left above write_row at the end are already 0!

    Column 1 in Example 1:  [8, 3, 4(matched), 8]
    Start: result col 1 = [0, 0, 0, 0], write_row = 3
    
    r = 3 (val 8, not matched) -> result[3][1] = 8, write_row = 2
    r = 2 (val 4, MATCHED)     -> skip!             write_row stays 2
    r = 1 (val 3, not matched) -> result[2][1] = 3, write_row = 1
    r = 0 (val 8, not matched) -> result[1][1] = 8, write_row = 0
    
    Final col 1: [0, 8, 3, 8]  (row 0 stays 0)
    
        # Phase 2 — Clear and drop: start `result` full of 0s so empty slots at the top are already 0,
        # and the caller's input `grid` is never mutated.
        result = [[0] * cols for _ in range(rows)]
        for c in range(cols):
            # Scan each column from the bottom row up so surviving tiles keep their top-to-bottom order.
            write_row = rows - 1
            for r in range(rows - 1, -1, -1):
                if not matched[r][c]:
                    result[write_row][c] = grid[r][c]
                    write_row -= 1
    
        return matches, result
    
  5. Walk through Example 1 end to end

    Let's trace the full algorithm on grid = [[4, 8, 2, 9], [4, 3, 6, 9], [4, 4, 4, 4], [7, 8, 5, 9]]:

    Input grid          matched mask             Dropped result
    4  8  2  9          T  .  .  .               0  0  0  0
    4  3  6  9   --->   T  .  .  .   --->        0  8  2  9
    4  4  4  4          T  T  T  T               0  3  6  9
    7  8  5  9          .  .  .  .               7  8  5  9
    
    1. Horizontal scan: Only row 2 ([4, 4, 4, 4]) has a streak of length >= 3. matches becomes [[4, 4]] and all four cells of row 2 become True.
    2. Vertical scan:
      • Column 0 ([4, 4, 4, 7]): run (0, 3) -> matches becomes [[4, 4], [4, 3]], and rows 0..2 of column 0 are marked True (cell (2, 0) was already True).
      • Column 1 ([8, 3, 4, 8]): max run length 1 -> none.
      • Column 2 ([2, 6, 4, 5]): max run length 1 -> none.
      • Column 3 ([9, 9, 4, 9]): the 4 splits the 9s into [9, 9] and [9], so max run length is 2 -> none.
    3. Clear and drop:
      • Column 0 loses rows 0..2, leaving [0, 0, 0, 7].
      • Columns 1, 2, and 3 each lose their row-2 cell, so rows 0 and 1 slide down by 1 and a 0 appears at the top.

    Notice that column 3 in result now holds [0, 9, 9, 9] — three 9s stacked vertically — and we stop here because only a single clear-and-drop pass is performed.

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def find_runs(line: List[int]) -> List[Tuple[int, int]]:
        """Return (start_index, run_length) for every maximal run of >= 3 equal values."""
        # runs: list of (start_index, run_length) pairs in left-to-right order
        runs = []
        start = 0
    
        # Two-pointer group scan: `start` anchors a streak, `end` walks until the value changes.
        while start < len(line):
            end = start
            while end < len(line) and line[end] == line[start]:
                end += 1
    
            run_length = end - start
            if run_length >= 3:
                runs.append((start, run_length))
    
            # Jump `start` straight to `end` so every streak is maximal and never split or double-counted.
            start = end
    
        return runs
    
    
    def match_three(grid: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]:
        rows = len(grid)
        cols = len(grid[0])
    
        # matches: list of [tile_value, run_length], e.g. [[4, 4], [4, 3]]
        matches = []
        # matched: rows x cols boolean mask; matched[r][c] is True when (r, c) is in >= 1 match.
        # Marking a separate mask instead of zeroing `grid` keeps original values intact for vertical checks.
        matched = [[False] * cols for _ in range(rows)]
    
        # Phase 1a — Horizontal matches: scan rows top to bottom, each row left to right.
        for r in range(rows):
            for start, run_length in find_runs(grid[r]):
                matches.append([grid[r][start], run_length])
                for c in range(start, start + run_length):
                    matched[r][c] = True
    
        # Phase 1b — Vertical matches: scan columns left to right, each column top to bottom.
        for c in range(cols):
            column = []
            for r in range(rows):
                column.append(grid[r][c])
            for start, run_length in find_runs(column):
                matches.append([column[start], run_length])
                for r in range(start, start + run_length):
                    matched[r][c] = True
    
        # Phase 2 — Clear and drop: start `result` full of 0s so empty slots at the top are already 0,
        # and the caller's input `grid` is never mutated.
        result = [[0] * cols for _ in range(rows)]
        for c in range(cols):
            # Scan each column from the bottom row up so surviving tiles keep their top-to-bottom order.
            write_row = rows - 1
            for r in range(rows - 1, -1, -1):
                if not matched[r][c]:
                    result[write_row][c] = grid[r][c]
                    write_row -= 1
    
        return matches, result
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine grading a tile puzzle by laying a clear plastic sheet over the board before removing any pieces. First, you scan every row with a marker and highlight any unbroken horizontal streak of 3 or more matching tiles on the plastic sheet, jotting each streak down on a notepad. Next, while the original board underneath is still completely intact, you scan every column and highlight any vertical streak of 3 or more matching tiles on that same sheet. Only after every horizontal and vertical streak has been marked do you remove all highlighted tiles at once and let the remaining tiles in each column slide down like checkers in a Connect Four frame. In code, that plastic sheet is a boolean mask — a rows x cols grid of True/False flags that remembers which cells belong to at least one match without altering the input grid.

Why do the first-instinct approaches go wrong? Checking fixed 3-cell windows (grid[r][c] == grid[r][c+1] == grid[r][c+2]) finds the right cells to clear, but it splits a 4-tile streak [4, 4, 4, 4] into two overlapping triples [4, 3] and [4, 3] instead of reporting one maximal run (the longest contiguous streak of equal values that cannot be extended at either end) [4, 4]. Worse, if you set matched cells to 0 right away during the row scan, any vertical match that crosses that row now sees a 0 at the intersection and breaks in half. Separating detection (with two-pointer run grouping and a boolean mask) from gravity (with two-pointer compaction, which copies surviving elements into position using separate read and write indices) avoids both bugs cleanly.

Here is a 3 x 4 trace (Example 2) where row 1 and column 1 share cell (1, 1):

Input board          1. Horizontal + Vertical scan      2. Bottom-up column drop
5  9  2  6           .  T  .  .                         5  0  0  0
3  9  9  9   --->    .  T  T  T   row 1 -> [9, 3]  ---> 3  0  2  6
8  9  4  1           .  T  .  .   col 1 -> [9, 3]       8  0  4  1

Cell (1, 1) stays 9 throughout both scans so matches = [[9, 3], [9, 3]] records both streaks, and in the drop step 2 and 6 from row 0 slide down into row 1 while column 1 becomes all 0s.

Complexity

Let m be the number of rows and n be the number of columns (m * n total cells).

  • Time: O(m * n). In find_runs, the end pointer advances across each cell of a line once and start jumps directly to end, so scanning all m rows takes O(m * n) work and scanning all n columns takes another O(m * n) work. Marking matched touches each cell at most twice (once horizontally, once vertically), and the bottom-up gravity pass reads each of the m * n cells once.
  • Space: O(m * n). Both the matched boolean mask and the returned result grid hold m * n entries, the temporary column list holds m integers at a time, and matches holds at most 2 * m * n / 3 pairs because runs in the same direction are disjoint and each has length at least 3.

Edge cases

  • No matches anywhere: matches is [], every matched[r][c] stays False, and the bottom-up copy writes every cell back to its original row, returning an exact copy of grid.
  • 1 x 1 grid or boards narrower/shorter than 3: find_runs simply finds no streak with run_length >= 3 along the short dimension.
  • Runs of 4 or more ([9, 9, 9, 9, 9]): reported once at full length ([9, 5]), never as overlapping triples.
  • Same value separated by a blocker ([6, 6, 6, 1, 6, 6, 6, 6]): reported as two distinct matches [[6, 3], [6, 4]] in left-to-right order.
  • Cross / T / L intersections: a cell shared by a horizontal run and a vertical run contributes to both entries in matches and is cleared once in result.
  • Entire board filled with one number: every row (when n >= 3) and every column (when m >= 3) is reported, and result becomes all 0s.
  • New 3-in-a-row formed after dropping (such as column 3 in Example 1): left untouched in result, because only a single find-clear-drop pass is performed.

Common mistakes

  • Sliding a window of size 3 to build matches: checking line[i] == line[i+1] == line[i+2] double-counts runs of length 4 or more unless you merge overlapping windows afterward. Jumping start = end finds maximal runs directly.
  • Zeroing cells during the horizontal scan: mutating grid[r][c] = 0 before scanning columns erases shared intersection cells and misses vertical matches.
  • Sorting matches by (row, col) coordinates: all horizontal matches must precede all vertical matches, and vertical matches must be ordered column by column (c = 0, 1, ...), not by the row where they start.
  • Reading top-down while writing bottom-up during the drop: scanning r from 0 to rows - 1 while decrementing write_row from rows - 1 flips each column upside down! Both r and write_row must move from bottom (rows - 1) to top (0).
  • Mutating the caller's grid: writing into a fresh result grid preserves the input and automatically fills the vacated top cells with 0.

Alternative approaches

  • Negative-sign marking in place (when mutating the input is allowed): Classic board-crushing implementations negate matched cells (grid[r][c] = -abs(grid[r][c])) during the scans and compare abs(grid[r][c]) when checking runs, avoiding the O(m * n) matched boolean grid. Here we must return a new result grid anyway, so an explicit matched boolean mask is much clearer and works even if 0 or negative numbers were ever allowed.
  • Column list slicing for gravity: In each column, collect [grid[r][c] for r in range(rows) if not matched[r][c]] and pad [0] * (rows - len(survivors)) on top. That takes the same O(m * n) time; the write_row pointer avoids allocating extra per-column lists.

Follow-up questions

  • How would you extend the simulation to repeat clearing and gravity until the board stabilizes with no remaining streaks? Wrap the single-round pass in a while True loop that terminates as soon as a round produces an empty matches list, and update find_runs to ignore 0 (if line[start] == 0: start += 1; continue) so vacated top slots never count as streaks! Because no new tiles spawn from above, every non-final round permanently removes at least 3 positive cells, capping the number of rounds at (m * n) / 3 and total runtime at O((m * n)^2).
  • Given a stable board, how can you test in O(1) time whether swapping two neighboring cells produces at least one match? Starting from a board with zero existing matches, any newly created streak of length >= 3 must pass through at least one of the two swapped coordinates. Temporarily swap the pair, inspect only the horizontal and vertical streaks through those two positions — walking at most 2 cells left, right, up, and down from each coordinate (at most 18 neighbor comparisons total) — and swap them back afterward.
  • What if overlapping horizontal and vertical streaks of the same value should be grouped together as a single L- or T-shaped combo? Assign each detected horizontal streak an integer group ID on an ID grid instead of a plain boolean mask, and use Union-Find (a disjoint-set data structure that merges overlapping groups in nearly O(1) time) whenever a vertical streak crosses a horizontal streak of the same tile value. Connected components containing two or more merged runs correspond directly to L, T, or cross combos.

Follow-up questions

Similar questions

More Roblox interview questions

All 84 Roblox questions →