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 >= 3identical 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.- 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. - 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.
- Scan rows from top (
- 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, leaving0in 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
3or more inresult, leave them untouched. When no matches exist, return([], result)whereresultequalsgrid.
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
2contains four consecutive4s, producing the horizontal match[4, 4]. - Column
0contains three consecutive4s in rows0..2, producing the vertical match[4, 3](listed after the horizontal match even though it starts at row0, and sharing cell(2, 0)). - Column
3holds[9, 9, 4, 9]: the4breaks the9s into lengths2and1, so no match occurs there during detection. - Clearing row
2and rows0..2of column0leaves7at the bottom of column0, while columns1,2, and3each drop their top two cells down by one row. Even though column3now ends with three9s ([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, wherem = len(grid)and every row has lengthn1 <= grid[r][c] <= 10^9
Step-by-step walkthrough
Understand the problem and the two key traps
We are given an
m x ngrid of positive integers and must simulate one single pass of streak detection and column gravity (without subsequent chain reactions), returning(matches, result):matches: a list of[value, length]pairs for every maximal run (the longest unbroken streak of equal adjacent numbers) of length3or more — all horizontal matches first (rows top to bottom, left to right), followed by all vertical matches (columns left to right, top to bottom).result: the grid after replacing every matched cell with0and 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
0immediately, the vertical scan would see a0at 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/Falsemaskmatched, then clear and drop into a freshresultgrid.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
lineinto maximal contiguous streaks of equal numbers, and keep the streaks whose length is at least3.We use two indices,
startandend:startsits on the first element of the current streak.endadvances rightward as long asline[end] == line[start].- When
endstops (either at a different value or atlen(line)),end - startis the full streak length. - Setting
start = endjumps 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 runsScan rows first, then columns, into a boolean mask
Now we apply
find_runsto every row and then every column:- Horizontal pass: loop
rfrom0torows - 1. Each rowgrid[r]is already a list, sofind_runs(grid[r])finds horizontal matches left to right. Append[grid[r][start], run_length]tomatchesand markmatched[r][c] = Truefor every cell in that run. - Vertical pass: loop
cfrom0tocols - 1. Extract columnctop to bottom into a temporary listcolumn, runfind_runs(column), append[column[start], run_length]tomatches, and markmatched[r][c] = Truefor 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 settingmatched[r][c] = Truea second time harmlessly leaves itTrue.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- Horizontal pass: loop
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 colsgridresultinitialized to all0s. For each columnc, place awrite_rowpointer at the bottom (rows - 1) and walk a read rowrfrom the bottom (rows - 1) up to0:- If
matched[r][c]isTrue, skip it — that cell was cleared. - If
matched[r][c]isFalse, copygrid[r][c]intoresult[write_row][c]and movewrite_rowup by1.
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 onrows - 2, and so on, preserving their original vertical order. Any slots left abovewrite_rowat the end are already0!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- If
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- Horizontal scan: Only row
2([4, 4, 4, 4]) has a streak of length>= 3.matchesbecomes[[4, 4]]and all four cells of row2becomeTrue. - Vertical scan:
- Column
0([4, 4, 4, 7]): run(0, 3)->matchesbecomes[[4, 4], [4, 3]], and rows0..2of column0are markedTrue(cell(2, 0)was alreadyTrue). - Column
1([8, 3, 4, 8]): max run length1-> none. - Column
2([2, 6, 4, 5]): max run length1-> none. - Column
3([9, 9, 4, 9]): the4splits the9s into[9, 9]and[9], so max run length is2-> none.
- Column
- Clear and drop:
- Column
0loses rows0..2, leaving[0, 0, 0, 7]. - Columns
1,2, and3each lose their row-2cell, so rows0and1slide down by1and a0appears at the top.
- Column
Notice that column
3inresultnow holds[0, 9, 9, 9]— three9s stacked vertically — and we stop here because only a single clear-and-drop pass is performed.- Horizontal scan: Only row
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). Infind_runs, theendpointer advances across each cell of a line once andstartjumps directly toend, so scanning allmrows takesO(m * n)work and scanning allncolumns takes anotherO(m * n)work. Markingmatchedtouches each cell at most twice (once horizontally, once vertically), and the bottom-up gravity pass reads each of them * ncells once. - Space:
O(m * n). Both thematchedboolean mask and the returnedresultgrid holdm * nentries, the temporarycolumnlist holdsmintegers at a time, andmatchesholds at most2 * m * n / 3pairs because runs in the same direction are disjoint and each has length at least3.
Edge cases
- No matches anywhere:
matchesis[], everymatched[r][c]staysFalse, and the bottom-up copy writes every cell back to its original row, returning an exact copy ofgrid. 1 x 1grid or boards narrower/shorter than 3:find_runssimply finds no streak withrun_length >= 3along 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
matchesand is cleared once inresult. - Entire board filled with one number: every row (when
n >= 3) and every column (whenm >= 3) is reported, andresultbecomes all0s. - New 3-in-a-row formed after dropping (such as column
3in Example 1): left untouched inresult, because only a single find-clear-drop pass is performed.
Common mistakes
- Sliding a window of size 3 to build
matches: checkingline[i] == line[i+1] == line[i+2]double-counts runs of length 4 or more unless you merge overlapping windows afterward. Jumpingstart = endfinds maximal runs directly. - Zeroing cells during the horizontal scan: mutating
grid[r][c] = 0before scanning columns erases shared intersection cells and misses vertical matches. - Sorting
matchesby(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
rfrom0torows - 1while decrementingwrite_rowfromrows - 1flips each column upside down! Bothrandwrite_rowmust move from bottom (rows - 1) to top (0). - Mutating the caller's
grid: writing into a freshresultgrid preserves the input and automatically fills the vacated top cells with0.
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 compareabs(grid[r][c])when checking runs, avoiding theO(m * n)matchedboolean grid. Here we must return a newresultgrid anyway, so an explicitmatchedboolean mask is much clearer and works even if0or 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 sameO(m * n)time; thewrite_rowpointer 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 Trueloop that terminates as soon as a round produces an emptymatcheslist, and updatefind_runsto ignore0(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) / 3and total runtime atO((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
>= 3must 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
- How would you extend the simulation to repeat clearing and gravity until the board stabilizes with no remaining streaks?
- Given a stable board, how can you test in O(1) time whether swapping two neighboring cells produces at least one match?
- What if overlapping horizontal and vertical streaks of the same value should be grouped together as a single L- or T-shaped combo?
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
- Grid Streak Removal and Column Gravity
- Per-Client Sliding Window Hit Counter
More Roblox interview questions
- Furthest Unblocked Cardinal Walk Around Grid Beams Medium
- Grid Streak Removal and Column Gravity 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