Candy Crush

Medium

Topics
ArrayTwo PointersMatrixSimulation

The board is a grid where each cell holds a positive candy type or 0 for empty.

Repeat until nothing changes:

  • Crush: every group of three or more equal, non-zero candies adjacent in a row or a column becomes empty. All such groups are crushed at the same time.
  • Drop: candies fall straight down into the empty space below them, and empties collect at the top of each column.

Return the final stable board. The rows are shown separated by |.

Example 1

before011112342567012
after000012342567012
vanishes on the first roundempty
Three or more equal values in a row or in a column vanish together, everything above them drops down into the gap, and the check runs again on the result until nothing more can go. The shaded cells are what disappears first; clearing them can line up a fresh run, which is why the rule repeats rather than applying once. It settled after 1 round here, and the lower grid is that stable board with 0 meaning empty.
Cells fall straight down only, and a zero is already-empty space rather than a value.
Input:  grid = [[1,1,1],[2,3,4],[5,6,7]]
Output: [[0,0,0],[2,3,4],[5,6,7]]
Explanation: The top row is three 1s, which crush; the rows below are already stable and simply stay put.

Example 2

before012311232123012
after000010002000012
vanishes on the first roundempty
Input:  grid = [[1,2,3],[1,2,3],[1,2,3]]
Output: [[0,0,0],[0,0,0],[0,0,0]]
Explanation: Every column is three of a kind, so the whole board goes at once.

Example 3

before0131113122323111012
after0000110121013202012
vanishes on the first roundempty
Input:  grid = [[1,3,1],[1,3,1],[2,3,2],[1,1,1]]
Output: [[0,0,0],[1,0,1],[1,0,1],[2,0,2]]
Explanation: The middle column of 3s and the bottom row of 1s crush together, then the survivors fall — and the result happens to be stable.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 3 <= m, n <= 50
  • 1 <= grid[i][j] <= 2000 or grid[i][j] == 0
Editorial — intuition, approach, complexity and pitfalls

Intuition

Two rules have to be kept apart, and mixing them is where solutions go wrong. Crushing is simultaneous — a candy that is part of two different groups is removed once, and crushing one group must not stop another group from being recognised. So crushing cannot zero cells as it finds them; it has to mark first and clear afterwards.

Finding the groups is a scan for runs of three or more equal non-zero values, once across each row and once down each column. A cell can be in a horizontal run and a vertical one at the same time, which is exactly why marking is a set rather than a count.

Dropping is independent of all that: each column settles on its own, and the easiest correct way to express it is to read the column from the bottom up, writing the non-zero values into the bottom of the column and filling the rest with zeros.

The loop runs until a pass finds nothing to crush. It terminates because every pass that does anything removes at least three candies and none are ever added.

Approach

  1. Mark phase: walk every row looking for runs of three or more equal non-zero values, and every column likewise. Record the positions in a set rather than clearing them.
  2. If nothing was marked, the board is stable — return it.
  3. Clear phase: set every marked position to 0.
  4. Drop phase: for each column, copy the surviving values downwards into the bottom of the column and zero what is left above.
  5. Repeat from the mark phase.

Walkthrough

grid = [[1,3,1],
        [1,3,1],
        [2,3,2],
        [1,1,1]]

mark phase finds two groups at once
   column 1, rows 0-2: three 3s
   row 3: three 1s
   marked: (0,1) (1,1) (2,1) (3,0) (3,1) (3,2)
           -- note (3,1) is in both groups and is marked once

after clearing
   1 . 1
   1 . 1
   2 . 2
   . . .

after dropping each column
   0 0 0
   1 0 1
   1 0 1
   2 0 2

second pass finds nothing: no run of three remains
answer [[0,0,0],[1,0,1],[1,0,1],[2,0,2]]

Complexity

  • Time — O((m * n)^2): each pass is a linear scan of the board, and every pass that changes anything removes at least three candies, so there are at most m*n/3 passes.
  • Space — O(m * n): the set of doomed positions.

Common Pitfalls

  • Zeroing candies while scanning. A cleared cell breaks the run that a later group depended on, so groups that should crush together do not — mark first, clear second.
  • Scanning runs of exactly three. Four in a row is one group of four, and checking overlapping triples covers it naturally; checking disjoint triples does not.
  • Forgetting that zero is not a candy. Three empty cells in a row are not a group, and omitting the non-zero test crushes empty space for ever.
  • Dropping by swapping neighbours once. A candy may have to fall several rows, so the column has to be rewritten rather than nudged.
  • Stopping after one crush-and-drop. A drop can create a new group, which is the whole reason for the loop.

Full Solution — all languages

class Solution:
    def candyCrush(self, grid):
        rows, cols = len(grid), len(grid[0])
        while True:
            doomed = set()
            for r in range(rows):
                for c in range(cols - 2):
                    v = grid[r][c]
                    if v and v == grid[r][c + 1] == grid[r][c + 2]:
                        doomed |= {(r, c), (r, c + 1), (r, c + 2)}
            for c in range(cols):
                for r in range(rows - 2):
                    v = grid[r][c]
                    if v and v == grid[r + 1][c] == grid[r + 2][c]:
                        doomed |= {(r, c), (r + 1, c), (r + 2, c)}
            if not doomed:
                return grid
            for r, c in doomed:
                grid[r][c] = 0
            for c in range(cols):
                write = rows - 1
                for r in range(rows - 1, -1, -1):
                    if grid[r][c]:
                        grid[write][c] = grid[r][c]
                        write -= 1
                for r in range(write, -1, -1):
                    grid[r][c] = 0
SensAI
Beta
Tap the mic to stop voice mode