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:

  1. 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.
  2. Clear simultaneously: Replace every matched cell from step 1 with 0 at 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.
  3. 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.
  4. 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) <= 50
  • 1 <= len(board[0]) <= 50
  • 0 <= board[r][c] <= 2000

Step-by-step walkthrough

  1. 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 n grid, positive integers represent candy types and 0 represents 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 to 0 simultaneously. 3. Gravity: In each column independently, drop remaining candies straight down so all 0s 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.

  2. 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 length k >= 3 is 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_cells bug-free: - Skip candy == 0: Empty cells at the top of the board are 0. If we allowed 0 == 0 == 0 to match, empty space would "crush" itself on every round and the while True loop would run forever! - Store coordinates in a set: Overlapping windows and row/column intersections naturally add the same (r, c) more than once, and a set deduplicates 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_crush
    
  3. Apply 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_row inspects every cell from bottom to top. - write_row marks 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_row starts at rows - 1 and moves up only when read_row moves up, write_row >= read_row always holds—so copying board[read_row][c] into board[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] = 0
    
  4. Repeat 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_gravity until find_crushable_cells returns 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 True loop guaranteed to finish? Every round that does not return removes at least 3 non-zero candies, and gravity only fills vacated top slots with 0—never creating new candies. On an m x n board, at most (m * n) // 3 crushing rounds can occur before the final stability check.

  5. Trace Example 1's multi-round cascade

    Watch how two rounds play out on Example 1's 4 x 4 board where Round 1 clears both a row and a column, dropping three 4s in column 0 together:

    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
    
    1. Round 1: Row 1 (3, 3, 3) and column 3 (6, 6, 6) are marked and zeroed simultaneously; [4, 9, 8] from row 0 drops into row 1.
    2. Round 2: Column 0 now has 4, 4, 4 in rows 1..3! (Row 0 has 0, 0, 0, 0, which is ignored because candy != 0.) Column 0 is zeroed, and nothing above it is non-zero.
    3. Round 3: find_crushable_cells returns set(), so the stable grid is returned.
  6. 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_cells checks at most m * (n - 2) horizontal windows and n * (m - 2) vertical windows in O(m * n) time, and apply_gravity scans each column once from bottom to top in O(m * n) time. Every round except the final check removes at least 3 candies and no candies ever respawn, so at most (m * n) // 3 + 1 rounds execute—multiplying O(m * n) work per round by O(m * n) rounds gives O((m * n)^2).
  • Space: O(m * n) because we work on a copy of the m x n grid and store at most m * n (row, col) tuples in cells_to_crush per round (while apply_gravity runs in O(1) extra space).

Edge cases

  • Already stable board: find_crushable_cells returns 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 into cells_to_crush before 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] = window 0..2 union window 1..3).
  • Empty 0 rows at the top after crushing: Explicitly ignored via candy != 0 so empty space never triggers another crush round.
  • 1-row or 1-column boards: When cols < 3 or rows < 3, Python's range(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 three 0s 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_row and write_row upward 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 comparing abs(val) during scanning) lets horizontal and vertical scans share one grid without allocating a Set or boolean matrix. During gravity, only strictly positive cells (board[r][c] > 0) survive.
  • Separate m x n boolean mask: Using marked = [[False] * cols for _ in range(rows)] avoids tuple hashing overhead while keeping the same O(m * n) space and clean read-then-write separation as Set[Tuple[int, int]].

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? Because the tag does not eat into width, every slice except possibly the last holds exactly width text characters, so the total chunk count n is fixed immediately by ceiling division (dividing and rounding up via (len(message) + width - 1) // width). You then slice message[(i - 1) * width : i * width] for i = 1 .. n and append f"<{i}/{n}>" in O(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's limit characters using the fewest chunks n (returning [] when impossible)? For a candidate total chunk count b, chunk a (1 <= a <= b) has a tag <a/b> of length 3 + len(str(a)) + len(str(b)), leaving limit - 3 - len(str(a)) - len(str(b)) characters for payload text; summing over a = 1 .. b gives total payload capacity b * (limit - 3 - len(str(b))) - sum_{a=1..b} len(str(a)). Watch out: capacity lacks monotonicity (a property where increasing b never decreases capacity)—for instance, at limit = 8, b = 9 holds 27 characters, whereas b = 10 drops to 19 characters because len(str(b)) grew from 1 to 2 on every chunk—so naive binary search on b fails! Instead, increment b = 1, 2, ... maintaining prefix_index_digits += len(str(b)) in O(1) per step: stop and return [] as soon as chunk b's tag leaves zero text room (3 + 2 * len(str(b)) >= limit), or greedily slice the string as soon as capacity >= len(message) (since capacity(b - 1) < len(message), the first b - 1 chunks can never exhaust the string early, guaranteeing chunk b is 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_crush in O(1) extra memory without a coordinate set? Use in-place sign marking directly on board: whenever three adjacent cells satisfy abs(board[r][c]) == abs(board[r][c+1]) == abs(board[r][c+2]) != 0, negate all three to -abs(val) and set found_any = True. Because abs(...) ignores the minus sign, horizontal marks never hide tiles from the vertical scan, and apply_gravity then treats only strictly positive cells (> 0) as surviving tiles—dropping auxiliary memory to O(1) while keeping the exact same O(m * n) time per round.

Follow-up questions

Similar questions

More TikTok interview questions

All 176 TikTok questions →