Cascade Grid Crushing and Width-Bounded Text Splitting
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
You are given an m x n integer grid board representing a 2D tile puzzle. Each positive integer board[r][c] > 0 denotes a tile of that type, while 0 denotes an empty slot.
Repeatedly eliminate matching lines and compact columns until the grid reaches a stable configuration:
- Detect all matches simultaneously: Identify every cell
(r, c)that belongs to a horizontal or vertical contiguous segment of 3 or more identical positive tile values (> 0). Empty slots (0) never match. - Clear simultaneously: Replace every matched cell from step 1 with
0at the same time. Because all matches are detected before any cell is cleared, intersecting horizontal and vertical segments (such as L, T, or+shapes) are eliminated together in the same round. - Apply column gravity: Within each column independently, let all surviving positive tiles slide straight down to fill empty slots below them while preserving their vertical relative order, and fill the vacated slots at the top of the column with
0. - Repeat until stable: If gravity creates new horizontal or vertical runs of 3 or more identical positive tiles, execute another round. Once a scan finds zero matching runs, return the stabilized 2D grid.
Implement candy_crush(board: List[List[int]]) -> List[List[int]].
Examples
Example 1
Input:
board = [
[4, 9, 8, 6],
[3, 3, 3, 6],
[4, 5, 7, 6],
[4, 2, 1, 5]
]
Output:
[
[0, 0, 0, 0],
[0, 9, 8, 0],
[0, 5, 7, 0],
[0, 2, 1, 5]
]
Walk-through: In Round 1, row 1 has [3, 3, 3] at (1, 0..2) and column 3 has [6, 6, 6] at (0..2, 3). Clearing all six cells and applying gravity drops [4, 9, 8] down one row, turning column 0 into [0, 4, 4, 4]. In Round 2, those three aligned 4s in column 0 are cleared to 0 while the empty top row of 0s is ignored. Round 3 finds no matches.
Example 2
Input:
board = [
[7, 2, 4, 8],
[7, 6, 9, 1],
[7, 7, 7, 3]
]
Output:
[
[0, 0, 0, 8],
[0, 2, 4, 1],
[0, 6, 9, 3]
]
Walk-through: Column 0 ((0..2, 0)) and row 2 ((2, 0..2)) share corner (2, 0) in an L-shaped group of 7s. Marking before clearing removes all five 7s in Round 1, after which [2, 6] and [4, 9] drop down one slot in columns 1 and 2.
Example 3
Input:
board = [
[5, 5, 2, 9],
[3, 5, 2, 2]
]
Output:
[
[5, 5, 2, 9],
[3, 5, 2, 2]
]
Walk-through: Pairs of 5s and 2s appear, and three 5s form a bent corner rather than a straight 3-cell line, so zero runs qualify and the grid is returned unchanged.
Constraints
1 <= len(board) <= 501 <= len(board[0]) <= 500 <= board[r][c] <= 2000
Step-by-step walkthrough
Understand the game loop and simultaneous crushing
This interview prompt pairs two classic problems; the automated judge tests the grid simulation
candy_crush(board)(and the companion message-splitting problem with<i/n>suffixes is walked through with full code in the explanation's follow-up section).On our
m x ngrid, positive integers represent candy types and0represents an empty cell. Each round follows three strict steps: 1. Mark: Find every cell that belongs to a horizontal or vertical line of 3 or more identical non-zero candies. 2. Crush: Set all marked cells to0simultaneously. 3. Gravity: In each column independently, drop remaining candies straight down so all0s float to the top.Why must marking finish completely before crushing begins? Look at an L-shaped match sharing a corner candy at
(2, 0):1 4 5 If we erased row 2 first: 0 4 5 1 6 7 ---> corner (2, 0) becomes 0 ---> 1 6 7 (now column 0 only has TWO 1s!) 1 1 1 before column 0 is checked! 0 0 0 <- BUG: column 0 fails to crush!By scanning the untouched board to collect coordinates first—and writing
0s only after both horizontal and vertical scans finish—shared corners in L, T, and+shapes are always handled accurately.Find runs of 3+ using sliding windows of size 3
What if a row has 4 or 5 matching candies in a row, like
[7, 7, 7, 7]? You do not need variable-length run-counting loops! Every run of lengthk >= 3is simply the union of its overlapping 3-cell windows:Row: [ 7, 7, 7, 7 ] Window 0: [ 7, 7, 7 ] -> marks indices 0, 1, 2 Window 1: [ 7, 7, 7 ] -> marks indices 1, 2, 3 Union in set: {0, 1, 2, 3} (all 4 cells marked!)Two small details keep
find_crushable_cellsbug-free: - Skipcandy == 0: Empty cells at the top of the board are0. If we allowed0 == 0 == 0to match, empty space would "crush" itself on every round and thewhile Trueloop would run forever! - Store coordinates in aset: Overlapping windows and row/column intersections naturally add the same(r, c)more than once, and asetdeduplicates them automatically.from typing import List, Set, Tuple def find_crushable_cells(board: List[List[int]]) -> Set[Tuple[int, int]]: """Return all (row, col) coordinates belonging to a 3+ horizontal or vertical run.""" rows = len(board) cols = len(board[0]) cells_to_crush: Set[Tuple[int, int]] = set() # Check every horizontal 3-cell window; runs of 4+ are covered by overlapping 3-windows. for r in range(rows): for c in range(cols - 2): candy = board[r][c] # Must skip 0 (empty cells), otherwise empty rows would "crush" forever. if candy != 0 and board[r][c + 1] == candy and board[r][c + 2] == candy: cells_to_crush.add((r, c)) cells_to_crush.add((r, c + 1)) cells_to_crush.add((r, c + 2)) # Check every vertical 3-cell window on the same unmodified board snapshot. for c in range(cols): for r in range(rows - 2): candy = board[r][c] if candy != 0 and board[r + 1][c] == candy and board[r + 2][c] == candy: cells_to_crush.add((r, c)) cells_to_crush.add((r + 1, c)) cells_to_crush.add((r + 2, c)) return cells_to_crushApply gravity column by column with a write pointer
Once marked cells are set to
0, each column compacts downward independently. Instead of building temporary column lists, we walk each column from bottom (rows - 1) to top (0) with two row indices: -read_rowinspects every cell from bottom to top. -write_rowmarks the lowest slot waiting for the next surviving candy.Single column (top -> bottom): [ 5, 0, 8, 0, 3 ] 0 1 2 3 4 <- row index read_row=4 (3 != 0): write 3 at write_row=4 -> write_row becomes 3 read_row=3 (0 == 0): skip read_row=2 (8 != 0): write 8 at write_row=3 -> write_row becomes 2 read_row=1 (0 == 0): skip read_row=0 (5 != 0): write 5 at write_row=2 -> write_row becomes 1 Fill rows 1 down to 0 with 0 -> final column: [ 0, 0, 5, 8, 3 ]Because
write_rowstarts atrows - 1and moves up only whenread_rowmoves up,write_row >= read_rowalways holds—so copyingboard[read_row][c]intoboard[write_row][c]never overwrites a cell we haven't read yet!def apply_gravity(board: List[List[int]]) -> None: """Slide remaining non-zero candies down each column and fill vacated top cells with 0.""" rows = len(board) cols = len(board[0]) for c in range(cols): write_row = rows - 1 for read_row in range(rows - 1, -1, -1): if board[read_row][c] != 0: board[write_row][c] = board[read_row][c] write_row -= 1 for empty_row in range(write_row, -1, -1): board[empty_row][c] = 0Repeat rounds until the board stabilizes
Gravity can drop surviving candies into brand-new 3-in-a-row alignments (chain reactions), so we cannot stop after a single round. We repeat
find_crushable_cells -> zero out -> apply_gravityuntilfind_crushable_cellsreturns an empty set:def candy_crush(board: List[List[int]]) -> List[List[int]]: if not board or not board[0]: return [row[:] for row in board] grid = [row[:] for row in board] while True: cells_to_crush = find_crushable_cells(grid) if not cells_to_crush: return grid for r, c in cells_to_crush: grid[r][c] = 0 apply_gravity(grid)Why is this
while Trueloop guaranteed to finish? Every round that does not return removes at least 3 non-zero candies, and gravity only fills vacated top slots with0—never creating new candies. On anm x nboard, at most(m * n) // 3crushing rounds can occur before the final stability check.Trace Example 1's multi-round cascade
Watch how two rounds play out on Example 1's
4 x 4board where Round 1 clears both a row and a column, dropping three4s in column0together:Start: Round 1 mark: After crush + gravity: Round 2 mark: Stable result: 4 9 8 6 4 9 8 *6* 0 0 0 0 0 0 0 0 0 0 0 0 3 3 3 6 ---> *3* *3* *3* *6* ---> 4 9 8 0 ---> *4* 9 8 0 ---> 0 9 8 0 4 5 7 6 4 5 7 *6* 4 5 7 0 *4* 5 7 0 0 5 7 0 4 2 1 5 4 2 1 5 4 2 1 5 *4* 2 1 5 0 2 1 5- Round 1: Row
1(3, 3, 3) and column3(6, 6, 6) are marked and zeroed simultaneously;[4, 9, 8]from row0drops into row1. - Round 2: Column
0now has4, 4, 4in rows1..3! (Row0has0, 0, 0, 0, which is ignored becausecandy != 0.) Column0is zeroed, and nothing above it is non-zero. - Round 3:
find_crushable_cellsreturnsset(), so the stable grid is returned.
- Round 1: Row
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def find_crushable_cells(board: List[List[int]]) -> Set[Tuple[int, int]]: """Return all (row, col) coordinates belonging to a 3+ horizontal or vertical run.""" rows = len(board) cols = len(board[0]) # cells_to_crush: set of (row, col) coordinates, e.g. {(1, 0), (1, 1), (1, 2)}. # Collecting into a set before mutating preserves L/T intersections during scanning. cells_to_crush: Set[Tuple[int, int]] = set() # Check every horizontal 3-cell window; runs of 4+ are covered by overlapping 3-windows. for r in range(rows): for c in range(cols - 2): candy = board[r][c] # Must skip 0 (empty cells), otherwise empty rows would "crush" forever. if candy != 0 and board[r][c + 1] == candy and board[r][c + 2] == candy: cells_to_crush.add((r, c)) cells_to_crush.add((r, c + 1)) cells_to_crush.add((r, c + 2)) # Check every vertical 3-cell window on the same unmodified board snapshot. for c in range(cols): for r in range(rows - 2): candy = board[r][c] if candy != 0 and board[r + 1][c] == candy and board[r + 2][c] == candy: cells_to_crush.add((r, c)) cells_to_crush.add((r + 1, c)) cells_to_crush.add((r + 2, c)) return cells_to_crush def apply_gravity(board: List[List[int]]) -> None: """Slide remaining non-zero candies down each column and fill vacated top cells with 0.""" rows = len(board) cols = len(board[0]) for c in range(cols): # write_row points to the lowest slot in column c not yet filled with a surviving candy. write_row = rows - 1 for read_row in range(rows - 1, -1, -1): if board[read_row][c] != 0: # write_row >= read_row always holds, so we never overwrite an unread cell. board[write_row][c] = board[read_row][c] write_row -= 1 # Every slot above the surviving candies becomes empty (0). for empty_row in range(write_row, -1, -1): board[empty_row][c] = 0 def candy_crush(board: List[List[int]]) -> List[List[int]]: if not board or not board[0]: return [row[:] for row in board] # Phase 1: Copy the grid so the caller's input list is not mutated unexpectedly. grid = [row[:] for row in board] # Phase 2: Repeatedly mark -> crush -> apply gravity until a round finds zero matches. # Each active round removes >= 3 candies and none respawn, so termination is guaranteed. while True: cells_to_crush = find_crushable_cells(grid) if not cells_to_crush: return grid for r, c in cells_to_crush: grid[r][c] = 0 apply_gravity(grid)✅ Submit now — all tests should pass.
Intuition & how it works
Think of each crushing round like placing sticky dots on a snapshot of the board before touching any pieces: first we inspect every 3-cell horizontal and vertical window and stick a dot on all three tiles whenever they match; second, we remove all dotted tiles at the exact same moment; third, we let surviving tiles in each column slide down to the bottom, leaving 0s (empty air) at the top. We repeat those three phases until a scan places zero sticky dots.
Why can't we take shortcuts—like erasing a run the instant we spot it, or running only one pass? If you erase a horizontal run immediately, a corner tile shared with a vertical run (an L or T shape) turns into 0 before the vertical scan reaches it, making the vertical run look only 2 tiles tall so it wrongly survives. And you cannot predict the final board in one pass because gravity after Round 1 can drop tiles from different heights into brand-new 3-in-a-row cascades.
Trace Example 1's 4 x 4 board ([[4, 9, 8, 6], [3, 3, 3, 6], [4, 5, 7, 6], [4, 2, 1, 5]]):
- Round 1: Scanning marks row 1's three 3s ((1, 0..2)) and column 3's three 6s ((0..2, 3)). Setting all six cells to 0 and compacting each column downward drops the top 4 from (0, 0) into (1, 0), turning column 0 into [0, 4, 4, 4].
- Round 2: Scanning skips the top row of 0s (candy != 0) and marks the three aligned 4s in column 0 ({(1, 0), (2, 0), (3, 0)}), clearing column 0 to [0, 0, 0, 0].
- Round 3: No 3-cell window matches, so the loop returns the stabilized board.
Complexity
Let the board have m rows and n columns (m * n total cells).
- Time: O((m * n)^2) in the worst case (
O(m * n)per round). In a single round,find_crushable_cellschecks at mostm * (n - 2)horizontal windows andn * (m - 2)vertical windows inO(m * n)time, andapply_gravityscans each column once from bottom to top inO(m * n)time. Every round except the final check removes at least3candies and no candies ever respawn, so at most(m * n) // 3 + 1rounds execute—multiplyingO(m * n)work per round byO(m * n)rounds givesO((m * n)^2). - Space: O(m * n) because we work on a copy of the
m x ngrid and store at mostm * n(row, col)tuples incells_to_crushper round (whileapply_gravityruns inO(1)extra space).
Edge cases
- Already stable board:
find_crushable_cellsreturns an empty set on Round 1 and the board comes back unchanged (Example 3). - Pairs of 2 identical candies: Never matched, because every check requires 3 adjacent identical cells.
- Intersecting L, T, and
+shapes: Marked intocells_to_crushbefore any cell is zeroed, so both the row run and the column run are crushed in the same round. - Runs of 4, 5, or whole rows/columns: Automatically covered by overlapping 3-cell windows (
[a, a, a, a]= window0..2union window1..3). - Empty
0rows at the top after crushing: Explicitly ignored viacandy != 0so empty space never triggers another crush round. - 1-row or 1-column boards: When
cols < 3orrows < 3, Python'srange(cols - 2)/range(rows - 2)is simply empty instead of going out of bounds.
Common mistakes
- Zeroing cells immediately while scanning. That destroys shared intersection cells before perpendicular runs are checked, leaving parts of L and T shapes uncrushed.
- Omitting
candy != 0. Once three0s sit side by side at the top of the board, they match each other every round and cause an infinite loop. - Running only a single crush-and-drop pass. Gravity often creates secondary matches (cascades), so the loop must continue until a pass finds zero matches.
- Bubble-swapping candies down one row per round. Gravity drops every floating candy all the way to the lowest available slot in its column within the same round, which two-pointer write compaction (walking a
read_rowandwrite_rowupward from the bottom of each column in one pass) achieves cleanly. - Reversing column order during gravity. If you collect surviving candies bottom-up into a list and write them top-down without reversing, the column flips upside down.
Alternative approaches
- In-place sign marking (
O(1)auxiliary space if mutating the input board is allowed): In-place sign marking (encoding a boolean "marked" flag by negating a cell's positive integer to-abs(val)while comparingabs(val)during scanning) lets horizontal and vertical scans share one grid without allocating aSetor boolean matrix. During gravity, only strictly positive cells (board[r][c] > 0) survive. - Separate
m x nboolean mask: Usingmarked = [[False] * cols for _ in range(rows)]avoids tuple hashing overhead while keeping the sameO(m * n)space and clean read-then-write separation asSet[Tuple[int, int]].
Follow-up questions
- Suppose a companion task asks you to chunk a string into slices of
widthcharacters and append a"<i/n>"tag outside the width budget—how do you build the slices? Because the tag does not eat intowidth, every slice except possibly the last holds exactlywidthtext characters, so the total chunk countnis fixed immediately by ceiling division (dividing and rounding up via(len(message) + width - 1) // width). You then slicemessage[(i - 1) * width : i * width]fori = 1 .. nand appendf"<{i}/{n}>"inO(len(message))total time.
python
def split_message_excluding_suffix(message: str, width: int) -> List[str]:
if not message:
return []
total_parts = (len(message) + width - 1) // width
result: List[str] = []
for idx in range(1, total_parts + 1):
start = (idx - 1) * width
chunk = message[start : start + width]
result.append(f"{chunk}<{idx}/{total_parts}>")
return result
- What if the
"<i/n>"tag itself must fit inside each chunk'slimitcharacters using the fewest chunksn(returning[]when impossible)? For a candidate total chunk countb, chunka(1 <= a <= b) has a tag<a/b>of length3 + len(str(a)) + len(str(b)), leavinglimit - 3 - len(str(a)) - len(str(b))characters for payload text; summing overa = 1 .. bgives total payload capacityb * (limit - 3 - len(str(b))) - sum_{a=1..b} len(str(a)). Watch out: capacity lacks monotonicity (a property where increasingbnever decreases capacity)—for instance, atlimit = 8,b = 9holds27characters, whereasb = 10drops to19characters becauselen(str(b))grew from1to2on every chunk—so naive binary search onbfails! Instead, incrementb = 1, 2, ...maintainingprefix_index_digits += len(str(b))inO(1)per step: stop and return[]as soon as chunkb's tag leaves zero text room (3 + 2 * len(str(b)) >= limit), or greedily slice the string as soon ascapacity >= len(message)(sincecapacity(b - 1) < len(message), the firstb - 1chunks can never exhaust the string early, guaranteeing chunkbis non-empty).
```python def split_message(message: str, limit: int) -> List[str]: msg_len = len(message) prefix_index_digits = 0 # running sum of len(str(a)) for a = 1..b
for b in range(1, msg_len + 1):
b_digits = len(str(b))
prefix_index_digits += b_digits
# Part b itself has the longest suffix: '<' + b + '/' + b + '>' = 3 + 2 * b_digits.
if 3 + 2 * b_digits >= limit:
return []
total_capacity = b * (limit - 3 - b_digits) - prefix_index_digits
if total_capacity >= msg_len:
parts: List[str] = []
cursor = 0
for a in range(1, b + 1):
suffix = f"<{a}/{b}>"
take = limit - len(suffix)
parts.append(message[cursor : cursor + take] + suffix)
cursor += take
return parts
return []
```
- If mutating the input matrix is allowed, how can you run
candy_crushin O(1) extra memory without a coordinate set? Use in-place sign marking directly onboard: whenever three adjacent cells satisfyabs(board[r][c]) == abs(board[r][c+1]) == abs(board[r][c+2]) != 0, negate all three to-abs(val)and setfound_any = True. Becauseabs(...)ignores the minus sign, horizontal marks never hide tiles from the vertical scan, andapply_gravitythen treats only strictly positive cells (> 0) as surviving tiles—dropping auxiliary memory toO(1)while keeping the exact sameO(m * n)time per round.
Follow-up questions
- Suppose a companion task asks you to chunk a string into slices of `width` characters and append a `"<i/n>"` tag outside the width budget—how do you build the slices?
- What if the `"<i/n>"` tag itself must fit inside each chunk's `limit` characters using the fewest chunks `n` (returning `[]` when impossible)?
- If mutating the input matrix is allowed, how can you run `candy_crush` in O(1) extra memory without a coordinate set?
Similar questions
- Comparing Uninformed and Heuristic Graph Search
- Mean of Distinct Values per Dictionary Key
- Outer Contour of a 2D Building Skyline
- Longest Strictly Increasing Subsequence Length
- Minimum Top-to-Bottom Sum in a Triangle
- Topological Execution Schedule for Pipelines
More TikTok interview questions
- Backend Project Deep Dive: Bottlenecks and Scaling Trade-Offs Medium
- Full-Lifecycle Walkthrough of a Demanding Engineering Initiative Medium
- Text Justification, Wildcard Parentheses, and Grid Shortest Path Medium Pro
- Fix a Partitioned Daily Active Users Query Medium Pro
- Flagship Project Walkthrough and Retrospective Medium Pro
- Thirty-Minute Software Engineering Project Deep Dive Medium Pro
- Presenting Industry Internship and Research ML Work Medium Pro
- Diagnosing and Resolving a Difficult Engineering Problem Medium Pro
- Constant-Time Least Recently Used Cache Medium Pro
- Dimensional Data Warehouse for Marketplace Metrics Hard Pro