Leetcode #723: Candy Crush
In this guide, we solve Leetcode #723 Candy Crush in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
This question is about implementing a basic elimination algorithm for Candy Crush. Given an m x n integer array board representing the grid of candy where board[i][j] represents the type of candy.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Array, Two Pointers, Matrix, Simulation
Intuition
The constraints hint that we can reason about two ends of the data at once, which is perfect for a two-pointer scan.
Moving one pointer at a time keeps the invariant intact and avoids nested loops.
Approach
Place pointers at the left and right ends and move them based on the comparison or target condition.
This yields a clean linear pass after any required sorting.
Steps:
- Set left and right pointers.
- Move a pointer based on the condition.
- Update the best answer while scanning.
Example
Input: board = [[110,5,112,113,114],[210,211,5,213,214],[310,311,3,313,314],[410,411,412,5,414],[5,1,512,3,3],[610,4,1,613,614],[710,1,2,713,714],[810,1,2,1,1],[1,1,2,2,2],[4,1,4,4,1014]]
Output: [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[110,0,0,0,114],[210,0,0,0,214],[310,0,0,113,314],[410,0,0,213,414],[610,211,112,313,614],[710,311,412,613,714],[810,411,512,713,1014]]
Python Solution
class Solution:
def candyCrush(self, board: List[List[int]]) -> List[List[int]]:
m, n = len(board), len(board[0])
run = True
while run:
run = False
for i in range(m):
for j in range(2, n):
if board[i][j] and abs(board[i][j]) == abs(board[i][j - 1]) == abs(
board[i][j - 2]
):
run = True
board[i][j] = board[i][j - 1] = board[i][j - 2] = -abs(
board[i][j]
)
for j in range(n):
for i in range(2, m):
if board[i][j] and abs(board[i][j]) == abs(board[i - 1][j]) == abs(
board[i - 2][j]
):
run = True
board[i][j] = board[i - 1][j] = board[i - 2][j] = -abs(
board[i][j]
)
if run:
for j in range(n):
k = m - 1
for i in range(m - 1, -1, -1):
if board[i][j] > 0:
board[k][j] = board[i][j]
k -= 1
while k >= 0:
board[k][j] = 0
k -= 1
return board
Complexity
The time complexity is , where and are the number of rows and columns of the matrix, respectively. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.