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'. You also have several colored balls in your hand.
Your goal is to clear all of the balls from the board. On each turn:
Pick any ball from your hand and insert it in between two balls in the row or on either end of the row.
If there is a group of three or more consecutive balls of the same color, remove the group of balls from the board.
If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left.
If there are no more balls on the board, then you win the game.
Repeat this process until you either win or do not have any more balls in your hand.
Given a string board, representing the row of balls on the board, and a string hand, representing the balls in your hand, return the minimum number of balls you have to insert to clear all the balls from the board. If you cannot clear all the balls from the board using the balls in your hand, return -1.
Example 1:
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.
Example 2:
Input: board = "WWRRBBWW", hand = "WRBRW"
Output: 2
Explanation: To make the board empty:
- Insert 'R' so the board becomes WWRRRBBWW. WWRRRBBWW -> WWBBWW.
- Insert 'B' so the board becomes WWBBBWW. WWBBBWW -> WWWW -> empty.
2 balls from your hand were needed to clear the board.
Example 3:
Input: board = "G", hand = "GGGGG"
Output: 2
Explanation: To make the board empty:
- Insert 'G' so the board becomes GG.
- Insert 'G' so the board becomes GGG. GGG -> empty.
2 balls from your hand were needed to clear the board.
Constraints:
1 <= board.length <= 16
1 <= hand.length <= 5
board and hand consist of the characters 'R', 'Y', 'B', 'G', and 'W'.
The initial row of balls on the board will not have any groups of three or more consecutive balls of the same color.
Problem summary: 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'. You also have several colored balls in your hand. Your goal is to clear all of the balls from the board. On each turn: Pick any ball from your hand and insert it in between two balls in the row or on either end of the row. If there is a group of three or more consecutive balls of the same color, remove the group of balls from the board. If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left. If there are no more balls on the board, then you win the game. Repeat this process until you either win or do not have any more balls in your hand. Given a string board, representing the row of balls on the
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming · Stack
Example 1
"WRRBBW"
"RB"
Example 2
"WWRRBBWW"
"WRBRW"
Example 3
"G"
"GGGGG"
Step 02
Core Insight
What unlocks the optimal approach
No official hints in dataset. Start from constraints and look for a monotonic or reusable state.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #488: Zuma Game
class Solution {
public int findMinStep(String board, String hand) {
final Zuma zuma = Zuma.create(board, hand);
final HashSet<Long> visited = new HashSet<>();
final ArrayList<Zuma> init = new ArrayList<>();
visited.add(zuma.board());
init.add(zuma);
return bfs(init, 0, visited);
}
private int bfs(ArrayList<Zuma> curr, int k, HashSet<Long> visited) {
if (curr.isEmpty()) {
return -1;
}
final ArrayList<Zuma> next = new ArrayList<>();
for (Zuma zuma : curr) {
ArrayList<Zuma> neib = zuma.getNextLevel(k, visited);
if (neib == null) {
return k + 1;
}
next.addAll(neib);
}
return bfs(next, k + 1, visited);
}
}
record Zuma(long board, long hand) {
public static Zuma create(String boardStr, String handStr) {
return new Zuma(Zuma.encode(boardStr, false), Zuma.encode(handStr, true));
}
public ArrayList<Zuma> getNextLevel(int depth, HashSet<Long> visited) {
final ArrayList<Zuma> next = new ArrayList<>();
final ArrayList<long[]> handList = this.buildHandList();
final long[] boardList = new long[32];
final int size = this.buildBoardList(boardList);
for (long[] pair : handList) {
for (int i = 0; i < size; ++i) {
final long rawBoard = pruningCheck(boardList[i], pair[0], i * 3, depth);
if (rawBoard == -1) {
continue;
}
final long nextBoard = updateBoard(rawBoard);
if (nextBoard == 0) {
return null;
}
if (pair[1] == 0 || visited.contains(nextBoard)) {
continue;
}
visited.add(nextBoard);
next.add(new Zuma(nextBoard, pair[1]));
}
}
return next;
}
private long pruningCheck(long insBoard, long ball, int pos, int depth) {
final long L = (insBoard >> (pos + 3)) & 0x7;
final long R = (insBoard >> (pos - 3)) & 0x7;
if (depth == 0 && (ball != R) && (L != R) || depth > 0 && (ball != R)) {
return -1;
}
return insBoard | (ball << pos);
}
private long updateBoard(long board) {
long stack = 0;
for (int i = 0; i < 64; i += 3) {
final long curr = (board >> i) & 0x7;
final long top = (stack) &0x7;
// pop (if possible)
if ((top > 0) && (curr != top) && (stack & 0x3F) == ((stack >> 3) & 0x3F)) {
stack >>= 9;
if ((stack & 0x7) == top) stack >>= 3;
}
if (curr == 0) {
// done
break;
}
// push and continue
stack = (stack << 3) | curr;
}
return stack;
}
private ArrayList<long[]> buildHandList() {
final ArrayList<long[]> handList = new ArrayList<>();
long prevBall = 0;
long ballMask = 0;
for (int i = 0; i < 16; i += 3) {
final long currBall = (this.hand >> i) & 0x7;
if (currBall == 0) {
break;
}
if (currBall != prevBall) {
prevBall = currBall;
handList.add(
new long[] {currBall, ((this.hand >> 3) & ~ballMask) | (this.hand & ballMask)});
}
ballMask = (ballMask << 3) | 0x7;
}
return handList;
}
private int buildBoardList(long[] buffer) {
int ptr = 0;
long ballMask = 0x7;
long insBoard = this.board << 3;
buffer[ptr++] = insBoard;
while (true) {
final long currBall = this.board & ballMask;
if (currBall == 0) {
break;
}
ballMask <<= 3;
insBoard = (insBoard | currBall) & ~ballMask;
buffer[ptr++] = insBoard;
}
return ptr;
}
private static long encode(String stateStr, boolean sortFlag) {
final char[] stateChars = stateStr.toCharArray();
if (sortFlag) {
Arrays.sort(stateChars);
}
long stateBits = 0;
for (char ch : stateChars) {
stateBits = (stateBits << 3) | Zuma.encode(ch);
}
return stateBits;
}
private static long encode(char ch) {
return switch (ch) {
case 'R' -> 0x1;
case 'G' -> 0x2;
case 'B' -> 0x3;
case 'W' -> 0x4;
case 'Y' -> 0x5;
case ' ' -> 0x0;
default ->
throw new IllegalArgumentException("Invalid char: " + ch);
};
}
}
// Accepted solution for LeetCode #488: Zuma Game
// Auto-generated Go example from java.
func exampleSolution() {
}
// Reference (java):
// // Accepted solution for LeetCode #488: Zuma Game
// class Solution {
// public int findMinStep(String board, String hand) {
// final Zuma zuma = Zuma.create(board, hand);
// final HashSet<Long> visited = new HashSet<>();
// final ArrayList<Zuma> init = new ArrayList<>();
//
// visited.add(zuma.board());
// init.add(zuma);
// return bfs(init, 0, visited);
// }
//
// private int bfs(ArrayList<Zuma> curr, int k, HashSet<Long> visited) {
// if (curr.isEmpty()) {
// return -1;
// }
//
// final ArrayList<Zuma> next = new ArrayList<>();
//
// for (Zuma zuma : curr) {
// ArrayList<Zuma> neib = zuma.getNextLevel(k, visited);
// if (neib == null) {
// return k + 1;
// }
//
// next.addAll(neib);
// }
// return bfs(next, k + 1, visited);
// }
// }
//
// record Zuma(long board, long hand) {
// public static Zuma create(String boardStr, String handStr) {
// return new Zuma(Zuma.encode(boardStr, false), Zuma.encode(handStr, true));
// }
//
// public ArrayList<Zuma> getNextLevel(int depth, HashSet<Long> visited) {
// final ArrayList<Zuma> next = new ArrayList<>();
// final ArrayList<long[]> handList = this.buildHandList();
// final long[] boardList = new long[32];
// final int size = this.buildBoardList(boardList);
//
// for (long[] pair : handList) {
// for (int i = 0; i < size; ++i) {
// final long rawBoard = pruningCheck(boardList[i], pair[0], i * 3, depth);
// if (rawBoard == -1) {
// continue;
// }
//
// final long nextBoard = updateBoard(rawBoard);
// if (nextBoard == 0) {
// return null;
// }
//
// if (pair[1] == 0 || visited.contains(nextBoard)) {
// continue;
// }
//
// visited.add(nextBoard);
// next.add(new Zuma(nextBoard, pair[1]));
// }
// }
// return next;
// }
//
// private long pruningCheck(long insBoard, long ball, int pos, int depth) {
// final long L = (insBoard >> (pos + 3)) & 0x7;
// final long R = (insBoard >> (pos - 3)) & 0x7;
//
// if (depth == 0 && (ball != R) && (L != R) || depth > 0 && (ball != R)) {
// return -1;
// }
// return insBoard | (ball << pos);
// }
//
// private long updateBoard(long board) {
// long stack = 0;
//
// for (int i = 0; i < 64; i += 3) {
// final long curr = (board >> i) & 0x7;
// final long top = (stack) &0x7;
//
// // pop (if possible)
// if ((top > 0) && (curr != top) && (stack & 0x3F) == ((stack >> 3) & 0x3F)) {
// stack >>= 9;
// if ((stack & 0x7) == top) stack >>= 3;
// }
//
// if (curr == 0) {
// // done
// break;
// }
// // push and continue
// stack = (stack << 3) | curr;
// }
// return stack;
// }
//
// private ArrayList<long[]> buildHandList() {
// final ArrayList<long[]> handList = new ArrayList<>();
// long prevBall = 0;
// long ballMask = 0;
//
// for (int i = 0; i < 16; i += 3) {
// final long currBall = (this.hand >> i) & 0x7;
// if (currBall == 0) {
// break;
// }
//
// if (currBall != prevBall) {
// prevBall = currBall;
// handList.add(
// new long[] {currBall, ((this.hand >> 3) & ~ballMask) | (this.hand & ballMask)});
// }
// ballMask = (ballMask << 3) | 0x7;
// }
// return handList;
// }
//
// private int buildBoardList(long[] buffer) {
// int ptr = 0;
// long ballMask = 0x7;
// long insBoard = this.board << 3;
// buffer[ptr++] = insBoard;
//
// while (true) {
// final long currBall = this.board & ballMask;
// if (currBall == 0) {
// break;
// }
//
// ballMask <<= 3;
// insBoard = (insBoard | currBall) & ~ballMask;
// buffer[ptr++] = insBoard;
// }
// return ptr;
// }
//
// private static long encode(String stateStr, boolean sortFlag) {
// final char[] stateChars = stateStr.toCharArray();
// if (sortFlag) {
// Arrays.sort(stateChars);
// }
//
// long stateBits = 0;
// for (char ch : stateChars) {
// stateBits = (stateBits << 3) | Zuma.encode(ch);
// }
// return stateBits;
// }
//
// private static long encode(char ch) {
// return switch (ch) {
// case 'R' -> 0x1;
// case 'G' -> 0x2;
// case 'B' -> 0x3;
// case 'W' -> 0x4;
// case 'Y' -> 0x5;
// case ' ' -> 0x0;
// default ->
// throw new IllegalArgumentException("Invalid char: " + ch);
// };
// }
// }
# Accepted solution for LeetCode #488: Zuma Game
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
// Accepted solution for LeetCode #488: Zuma Game
struct Solution;
use std::ops::Range;
impl Solution {
fn find_min_step(board: String, hand: String) -> i32 {
let n = hand.len();
let board: Vec<char> = board.chars().collect();
let hand: Vec<char> = hand.chars().collect();
let mut res = std::i32::MAX;
Self::dfs(0, 0, board, &mut res, &hand, n);
if res == std::i32::MAX {
-1
} else {
res
}
}
fn dfs(start: usize, state: u32, board: Vec<char>, res: &mut i32, hand: &[char], n: usize) {
if start == n {
return;
}
for i in 0..board.len() {
if i == 0 || board[i] != board[i - 1] {
if let Some(next_state) = Self::find_next_state(board[i], state, hand, n) {
let mut new_board: Vec<char> = board.to_vec();
new_board.insert(i, board[i]);
while let Some(range) = Self::dropable(&new_board) {
new_board.drain(range);
Self::dfs(start + 1, next_state, new_board.to_vec(), res, hand, n);
}
if new_board.is_empty() {
*res = (*res).min((start + 1) as i32);
} else {
Self::dfs(start + 1, next_state, new_board, res, hand, n);
}
}
}
}
}
fn find_next_state(c: char, state: u32, hand: &[char], n: usize) -> Option<u32> {
for i in 0..n {
if hand[i] == c && state & 1 << i == 0 {
return Some(state | 1 << i);
}
}
None
}
fn dropable(board: &[char]) -> Option<Range<usize>> {
let n = board.len();
let mut l = 0;
let mut r = 0;
while r < n {
if board[l] == board[r] {
r += 1;
} else {
if r - l >= 3 {
return Some(l..r);
} else {
l = r;
}
}
}
if r - l >= 3 {
return Some(l..r);
}
None
}
}
#[test]
fn test() {
let board = "WRRBBW".to_string();
let hand = "RB".to_string();
let res = -1;
assert_eq!(Solution::find_min_step(board, hand), res);
let board = "WWRRBBWW".to_string();
let hand = "WRBRW".to_string();
let res = 2;
assert_eq!(Solution::find_min_step(board, hand), res);
let board = "G".to_string();
let hand = "GGGGG".to_string();
let res = 2;
assert_eq!(Solution::find_min_step(board, hand), res);
let board = "RBYYBBRRB".to_string();
let hand = "YRBGB".to_string();
let res = 3;
assert_eq!(Solution::find_min_step(board, hand), res);
let board = "RRWWRRBBRR".to_string();
let hand = "WB".to_string();
let res = 2;
assert_eq!(Solution::find_min_step(board, hand), res);
}
// Accepted solution for LeetCode #488: Zuma Game
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #488: Zuma Game
// class Solution {
// public int findMinStep(String board, String hand) {
// final Zuma zuma = Zuma.create(board, hand);
// final HashSet<Long> visited = new HashSet<>();
// final ArrayList<Zuma> init = new ArrayList<>();
//
// visited.add(zuma.board());
// init.add(zuma);
// return bfs(init, 0, visited);
// }
//
// private int bfs(ArrayList<Zuma> curr, int k, HashSet<Long> visited) {
// if (curr.isEmpty()) {
// return -1;
// }
//
// final ArrayList<Zuma> next = new ArrayList<>();
//
// for (Zuma zuma : curr) {
// ArrayList<Zuma> neib = zuma.getNextLevel(k, visited);
// if (neib == null) {
// return k + 1;
// }
//
// next.addAll(neib);
// }
// return bfs(next, k + 1, visited);
// }
// }
//
// record Zuma(long board, long hand) {
// public static Zuma create(String boardStr, String handStr) {
// return new Zuma(Zuma.encode(boardStr, false), Zuma.encode(handStr, true));
// }
//
// public ArrayList<Zuma> getNextLevel(int depth, HashSet<Long> visited) {
// final ArrayList<Zuma> next = new ArrayList<>();
// final ArrayList<long[]> handList = this.buildHandList();
// final long[] boardList = new long[32];
// final int size = this.buildBoardList(boardList);
//
// for (long[] pair : handList) {
// for (int i = 0; i < size; ++i) {
// final long rawBoard = pruningCheck(boardList[i], pair[0], i * 3, depth);
// if (rawBoard == -1) {
// continue;
// }
//
// final long nextBoard = updateBoard(rawBoard);
// if (nextBoard == 0) {
// return null;
// }
//
// if (pair[1] == 0 || visited.contains(nextBoard)) {
// continue;
// }
//
// visited.add(nextBoard);
// next.add(new Zuma(nextBoard, pair[1]));
// }
// }
// return next;
// }
//
// private long pruningCheck(long insBoard, long ball, int pos, int depth) {
// final long L = (insBoard >> (pos + 3)) & 0x7;
// final long R = (insBoard >> (pos - 3)) & 0x7;
//
// if (depth == 0 && (ball != R) && (L != R) || depth > 0 && (ball != R)) {
// return -1;
// }
// return insBoard | (ball << pos);
// }
//
// private long updateBoard(long board) {
// long stack = 0;
//
// for (int i = 0; i < 64; i += 3) {
// final long curr = (board >> i) & 0x7;
// final long top = (stack) &0x7;
//
// // pop (if possible)
// if ((top > 0) && (curr != top) && (stack & 0x3F) == ((stack >> 3) & 0x3F)) {
// stack >>= 9;
// if ((stack & 0x7) == top) stack >>= 3;
// }
//
// if (curr == 0) {
// // done
// break;
// }
// // push and continue
// stack = (stack << 3) | curr;
// }
// return stack;
// }
//
// private ArrayList<long[]> buildHandList() {
// final ArrayList<long[]> handList = new ArrayList<>();
// long prevBall = 0;
// long ballMask = 0;
//
// for (int i = 0; i < 16; i += 3) {
// final long currBall = (this.hand >> i) & 0x7;
// if (currBall == 0) {
// break;
// }
//
// if (currBall != prevBall) {
// prevBall = currBall;
// handList.add(
// new long[] {currBall, ((this.hand >> 3) & ~ballMask) | (this.hand & ballMask)});
// }
// ballMask = (ballMask << 3) | 0x7;
// }
// return handList;
// }
//
// private int buildBoardList(long[] buffer) {
// int ptr = 0;
// long ballMask = 0x7;
// long insBoard = this.board << 3;
// buffer[ptr++] = insBoard;
//
// while (true) {
// final long currBall = this.board & ballMask;
// if (currBall == 0) {
// break;
// }
//
// ballMask <<= 3;
// insBoard = (insBoard | currBall) & ~ballMask;
// buffer[ptr++] = insBoard;
// }
// return ptr;
// }
//
// private static long encode(String stateStr, boolean sortFlag) {
// final char[] stateChars = stateStr.toCharArray();
// if (sortFlag) {
// Arrays.sort(stateChars);
// }
//
// long stateBits = 0;
// for (char ch : stateChars) {
// stateBits = (stateBits << 3) | Zuma.encode(ch);
// }
// return stateBits;
// }
//
// private static long encode(char ch) {
// return switch (ch) {
// case 'R' -> 0x1;
// case 'G' -> 0x2;
// case 'B' -> 0x3;
// case 'W' -> 0x4;
// case 'Y' -> 0x5;
// case ' ' -> 0x0;
// default ->
// throw new IllegalArgumentException("Invalid char: " + ch);
// };
// }
// }
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × m)
Space
O(n × m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Breaking monotonic invariant
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.