Candy Crush - Problem
Imagine you're playing the classic Candy Crush game! ๐ญ You have an m x n grid filled with colorful candies, where each candy is represented by a positive integer. Empty cells are represented by 0.
Your task is to simulate the candy crushing mechanics until the board reaches a stable state. Here's how it works:
- ๐ Find Matches: Identify groups of 3 or more identical candies aligned horizontally or vertically
- ๐ฅ Crush Simultaneously: Remove all matched candies at once (they become 0)
- ๐ Apply Gravity: Let remaining candies fall down to fill empty spaces
- ๐ Repeat: Continue until no more matches can be made
Return the final stable board configuration after all possible crushing is complete.
Note: No new candies appear from above - only existing candies fall due to gravity!
Input & Output
example_1.py โ Basic Horizontal Match
$
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],[512,2,3,3,3],[13,14,15,16,17]]
โบ
Output:
[[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[110,0,0,0,0],[210,5,0,5,0],[310,211,112,213,0],[410,311,3,313,114]]
๐ก Note:
The bottom row has three consecutive 3's which get crushed. After gravity, remaining candies fall down to fill empty spaces.
example_2.py โ Vertical Match
$
Input:
board = [[1,3,5,5,2],[3,4,3,3,1],[3,2,4,5,2],[2,4,4,5,5],[1,4,4,1,1]]
โบ
Output:
[[1,3,0,0,0],[3,4,0,0,0],[3,2,0,0,0],[2,4,0,0,0],[1,4,3,5,5]]
๐ก Note:
Multiple vertical matches (5,5,5 and 3,3,3) are found and crushed simultaneously, then gravity is applied.
example_3.py โ No Matches
$
Input:
board = [[1,2,3],[4,5,6],[7,8,9]]
โบ
Output:
[[1,2,3],[4,5,6],[7,8,9]]
๐ก Note:
No groups of 3+ identical candies exist, so the board remains unchanged.
Visualization
Tap to expand
Understanding the Visualization
1
Scan for Patterns
Look for horizontal and vertical lines of 3+ identical candies
2
Mark All Matches
Identify all positions that should be crushed simultaneously
3
Simultaneous Crush
Remove all marked candies at the same time
4
Apply Gravity
Drop remaining candies down to fill empty spaces
5
Check Stability
Repeat the process until no more matches exist
Key Takeaway
๐ฏ Key Insight: Mark all crushable candies first before removing any - this ensures proper simultaneous elimination as per game rules!
Time & Space Complexity
Time Complexity
O(k * m * n * (m + n))
k iterations of crushing, each requiring O(m*n) to find matches and O(m*n) for gravity
โ Linear Growth
Space Complexity
O(m * n)
Additional space for marking crushable positions
โก Linearithmic Space
Constraints
- m == board.length
- n == board[i].length
- 3 <= m, n <= 50
- 1 <= board[i][j] <= 2000
- board[i][j] == 0 represents an empty cell
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code