Candy Crush
Medium
Topics
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
0 meaning empty.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
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
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
- 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.
- If nothing was marked, the board is stable — return it.
- Clear phase: set every marked position to
0. - Drop phase: for each column, copy the surviving values downwards into the bottom of the column and zero what is left above.
- 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] = 0import java.util.*;
class Solution {
public int[][] candyCrush(int[][] grid) {
int rows = grid.length, cols = grid[0].length;
for (;;) {
Set<Integer> doomed = new HashSet<>();
for (int r = 0; r < rows; r++) {
for (int c = 0; c + 2 < cols; c++) {
int v = grid[r][c];
if (v != 0 && v == grid[r][c + 1] && v == grid[r][c + 2]) {
doomed.add(r * cols + c);
doomed.add(r * cols + c + 1);
doomed.add(r * cols + c + 2);
}
}
}
for (int c = 0; c < cols; c++) {
for (int r = 0; r + 2 < rows; r++) {
int v = grid[r][c];
if (v != 0 && v == grid[r + 1][c] && v == grid[r + 2][c]) {
doomed.add(r * cols + c);
doomed.add((r + 1) * cols + c);
doomed.add((r + 2) * cols + c);
}
}
}
if (doomed.isEmpty()) return grid;
for (int key : doomed) grid[key / cols][key % cols] = 0;
for (int c = 0; c < cols; c++) {
int write = rows - 1;
for (int r = rows - 1; r >= 0; r--) {
if (grid[r][c] != 0) {
grid[write][c] = grid[r][c];
write--;
}
}
for (int r = write; r >= 0; r--) grid[r][c] = 0;
}
}
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<vector<int>> candyCrush(vector<vector<int>>& grid) {
int rows = grid.size(), cols = grid[0].size();
for (;;) {
set<pair<int, int>> doomed;
for (int r = 0; r < rows; r++) {
for (int c = 0; c + 2 < cols; c++) {
int v = grid[r][c];
if (v && v == grid[r][c + 1] && v == grid[r][c + 2]) {
doomed.insert({r, c});
doomed.insert({r, c + 1});
doomed.insert({r, c + 2});
}
}
}
for (int c = 0; c < cols; c++) {
for (int r = 0; r + 2 < rows; r++) {
int v = grid[r][c];
if (v && v == grid[r + 1][c] && v == grid[r + 2][c]) {
doomed.insert({r, c});
doomed.insert({r + 1, c});
doomed.insert({r + 2, c});
}
}
}
if (doomed.empty()) return grid;
for (auto& cell : doomed) grid[cell.first][cell.second] = 0;
for (int c = 0; c < cols; c++) {
int write = rows - 1;
for (int r = rows - 1; r >= 0; r--) {
if (grid[r][c]) {
grid[write][c] = grid[r][c];
write--;
}
}
for (int r = write; r >= 0; r--) grid[r][c] = 0;
}
}
}
};/**
* @param {number[][]} grid
* @return {number[][]}
*/ var candyCrush = function(grid) {
const rows = grid.length, cols = grid[0].length;
for (;;) {
const doomed = new Set();
for (let r = 0; r < rows; r++) {
for (let c = 0; c + 2 < cols; c++) {
const v = grid[r][c];
if (v && v === grid[r][c + 1] && v === grid[r][c + 2]) {
doomed.add(r + "," + c);
doomed.add(r + "," + (c + 1));
doomed.add(r + "," + (c + 2));
}
}
}
for (let c = 0; c < cols; c++) {
for (let r = 0; r + 2 < rows; r++) {
const v = grid[r][c];
if (v && v === grid[r + 1][c] && v === grid[r + 2][c]) {
doomed.add(r + "," + c);
doomed.add((r + 1) + "," + c);
doomed.add((r + 2) + "," + c);
}
}
}
if (!doomed.size) return grid;
for (const key of doomed) {
const parts = key.split(",");
grid[+parts[0]][+parts[1]] = 0;
}
for (let c = 0; c < cols; c++) {
let write = rows - 1;
for (let r = rows - 1; r >= 0; r--) {
if (grid[r][c]) {
grid[write][c] = grid[r][c];
write--;
}
}
for (let r = write; r >= 0; r--) grid[r][c] = 0;
}
}
};