Leetcode #488: Zuma Game
In this guide, we solve Leetcode #488 Zuma Game 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
You are playing a variation of the game Zuma. In this variation of Zuma, there is a single row of colored balls on a board, where each ball can be colored red 'R', yellow 'Y', blue 'B', green 'G', or white 'W'.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Stack, Breadth-First Search, Memoization, String, Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: board = "WRRBBW", hand = "RB"
Output: -1
Explanation: It is impossible to clear all the balls. The best you can do is:
- Insert 'R' so the board becomes WRRRBBW. WRRRBBW -> WBBW.
- Insert 'B' so the board becomes WBBBW. WBBBW -> WW.
There are still balls remaining on the board, and you are out of balls to insert.
Python Solution
class Solution:
def findMinStep(self, board: str, hand: str) -> int:
def remove(s):
while len(s):
next = re.sub(r'B{3,}|G{3,}|R{3,}|W{3,}|Y{3,}', '', s)
if len(next) == len(s):
break
s = next
return s
visited = set()
q = deque([(board, hand)])
while q:
state, balls = q.popleft()
if not state:
return len(hand) - len(balls)
for ball in set(balls):
b = balls.replace(ball, '', 1)
for i in range(1, len(state) + 1):
s = state[:i] + ball + state[i:]
s = remove(s)
if s not in visited:
visited.add(s)
q.append((s, b))
return -1
Complexity
The time complexity is O(n·m) (typical). The space complexity is O(n·m) or optimized.
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.