Candy Crush — LeetCode 723 Python Solution
- Problem
- #723
- Pattern
- Two Pointers
- Reading time
- 6 min
- Source
- leetcode.com
The problem
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.
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 boardComplexity
| Measure | Complexity |
|---|---|
| Time | O(m^2 \times n^2), where m and n are the number of rows and columns of the matrix, respectively |
| Space | O(1) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 723. Candy Crush is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 723. Candy Crush?
- LeetCode 723. Candy Crush is rated Medium on LeetCode.
- What is the time complexity of LeetCode 723. Candy Crush?
- The Python solution on this page runs in O(m^2 \times n^2), where m and n are the number of rows and columns of the matrix, respectively.
- What is the space complexity of LeetCode 723. Candy Crush?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 723. Candy Crush cover?
- LeetCode 723. Candy Crush is tagged Array, Two Pointers, Matrix and Simulation on LeetCode.
- Is LeetCode 723. Candy Crush a premium problem?
- Yes. LeetCode 723. Candy Crush is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.