Imagine you're playing a strategic puzzle game similar to the classic Zuma! You have a row of colored balls on a board, where each ball can be 'R' (red), 'Y' (yellow), 'B' (blue), 'G' (green), or 'W' (white). In your hand, you have several additional colored balls that you can strategically place.
Your mission: Clear all balls from the board using the minimum number of balls from your hand!
Game Rules:
On each turn, pick any ball from your hand and insert it anywhere in the row (between two balls or at either end)
After insertion, if there are 3 or more consecutive balls of the same color, they disappear automatically
This removal might create new groups of 3+ consecutive balls - these also disappear in a chain reaction
Continue until no more groups can be removed
Win condition: All balls cleared from the board
Challenge: Given the initial board configuration and the balls in your hand, find the minimum number of balls you need to insert to clear the entire board. Return -1 if it's impossible.
Input & Output
example_1.py โ Basic Case
$Input:board = "WWRRBBWW", hand = "WRBRW"
โบOutput:2
๐ก Note:Place 'R' at position 2: "WWRRRBBWW" โ Remove RRR: "WWBBWW". Then place 'B' at position 3: "WWBBBWW" โ Remove BBB: "WWWW" โ Remove WWWW: "". Total: 2 moves.
example_2.py โ Impossible Case
$Input:board = "RWWWRR", hand = "RRB"
โบOutput:-1
๐ก Note:No matter how we place the balls from our hand, we cannot clear the entire board. The WWW in the middle cannot be removed with the available balls.
example_3.py โ Chain Reaction
$Input:board = "G", hand = "GGGGG"
โบOutput:2
๐ก Note:Place 'G' at position 0: "GG", then place another 'G': "GGG" โ Remove GGG: "". Total: 2 moves needed to form a group of 3.
Visualization
Tap to expand
Understanding the Visualization
1
Analyze the Board
Identify existing groups and potential trigger points where adding 1-2 balls could create groups of 3+
2
Strategic Placement
Only consider positions adjacent to existing groups of the same color - these are the 'strategic positions'
3
Chain Reaction Simulation
After each placement, simulate the complete chain reaction of removing 3+ consecutive balls
4
BFS Exploration
Use BFS to explore all possibilities level by level, ensuring we find the minimum number of moves
5
Memoization Cache
Remember already-computed board states to avoid redundant work
Key Takeaway
๐ฏ Key Insight: The optimal solution combines BFS for guaranteed minimum moves with strategic positioning to dramatically reduce the search space, making an otherwise exponential problem tractable through smart pruning and memoization.
Time & Space Complexity
Time Complexity
โฑ๏ธ
O(4^n * m)
Where n is the maximum depth (moves), m is board length for processing. Pruned by memoization.
n
2n
โ Linear Growth
Space Complexity
O(4^n * m)
BFS queue and memoization storage for unique states
Each ball color is one of 'R', 'Y', 'B', 'G', or 'W'
The input strings contain only the specified ball colors
Game rule: Groups of 3 or more consecutive same-colored balls are removed
Objective: Clear all balls using minimum insertions from hand
Asked in
G
Google 15a
Amazon 8f
Meta 12โ
Microsoft 6
Zuma Game โ Solution
The optimal approach uses BFS with memoization to explore game states level by level. Key optimizations include: (1) Strategic positioning - only try placing balls where they can form 3+ consecutive groups, (2) Memoization - cache board+hand combinations to avoid redundant computation, (3) BFS guarantee - level-by-level exploration ensures minimum moves. Time complexity is O(4^n ร m) where n is max moves and m is board length, but strategic pruning significantly reduces the search space in practice.
Common Approaches
Approach
Time
Space
Notes
โ
BFS with Memoization (Optimal)
O(4^n * m)
O(4^n * m)
Use BFS to explore states level by level with memoization to avoid revisiting states
Brute Force (Recursive Backtracking)
O(k^n * m)
O(n)
Try every possible ball placement at every position recursively
BFS with Memoization (Optimal) โ Algorithm Steps
Use BFS queue to explore states (board, hand) level by level
For each state, only try placing balls at strategic positions
Strategic positions: adjacent to existing groups of same color
Use memoization to cache results for (board, hand) combinations
Return the level when we first reach an empty board
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Level 0 (Initial)
Queue: [(RWWWRR, RRB, 0)] - Start with initial state
2
Level 1 Expansion
Try strategic positions only - near existing groups of same color
3
Memoization
Cache seen states to avoid recomputation: 'RWWWRR#BBR' โ visited
4
Strategic Pruning
Only try positions where we can potentially form 3+ consecutive balls
Code -
solution.c โ C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_QUEUE_SIZE 10000
#define MAX_STATE_LEN 50
typedef struct {
char board[MAX_STATE_LEN];
char hand[MAX_STATE_LEN];
int moves;
} State;
typedef struct {
State states[MAX_QUEUE_SIZE];
int front, rear, size;
} Queue;
void initQueue(Queue* q) {
q->front = q->rear = q->size = 0;
}
void enqueue(Queue* q, State s) {
if (q->size < MAX_QUEUE_SIZE) {
q->states[q->rear] = s;
q->rear = (q->rear + 1) % MAX_QUEUE_SIZE;
q->size++;
}
}
State dequeue(Queue* q) {
State s = q->states[q->front];
q->front = (q->front + 1) % MAX_QUEUE_SIZE;
q->size--;
return s;
}
bool isEmpty(Queue* q) {
return q->size == 0;
}
char* removeConsecutive(char* s) {
int len = strlen(s);
char* result = malloc(len + 1);
bool changed = true;
while (changed) {
changed = false;
int resultLen = 0;
int i = 0;
while (i < len) {
int j = i;
while (j < len && s[j] == s[i]) {
j++;
}
if (j - i >= 3) {
changed = true;
} else {
for (int k = i; k < j; k++) {
result[resultLen++] = s[k];
}
}
i = j;
}
result[resultLen] = '\0';
strcpy(s, result);
len = resultLen;
}
return s;
}
int* getStrategicPositions(char* board, int* count) {
int len = strlen(board);
int* positions = malloc((len + 10) * sizeof(int));
bool used[len + 10];
memset(used, false, sizeof(used));
*count = 0;
used[0] = true;
positions[(*count)++] = 0;
used[len] = true;
positions[(*count)++] = len;
for (int i = 0; i < len; i++) {
if (i > 0 && board[i] == board[i-1]) {
if (!used[i-1]) {
used[i-1] = true;
positions[(*count)++] = i-1;
}
if (!used[i+1] && i+1 <= len) {
used[i+1] = true;
positions[(*count)++] = i+1;
}
}
if (i < len - 1 && board[i] == board[i+1]) {
if (!used[i]) {
used[i] = true;
positions[(*count)++] = i;
}
if (!used[i+2] && i+2 <= len) {
used[i+2] = true;
positions[(*count)++] = i+2;
}
}
}
return positions;
}
int findMinStep(char* board, char* hand) {
Queue queue;
initQueue(&queue);
State initial;
strcpy(initial.board, board);
strcpy(initial.hand, hand);
initial.moves = 0;
enqueue(&queue, initial);
char memo[1000][MAX_STATE_LEN * 2];
int memoCount = 0;
while (!isEmpty(&queue)) {
State curr = dequeue(&queue);
if (strlen(curr.board) == 0) {
return curr.moves;
}
if (curr.moves >= 6) continue;
// Simple memoization check
char stateKey[MAX_STATE_LEN * 2];
sprintf(stateKey, "%s#%s", curr.board, curr.hand);
bool found = false;
for (int i = 0; i < memoCount; i++) {
if (strcmp(memo[i], stateKey) == 0) {
found = true;
break;
}
}
if (found) continue;
if (memoCount < 1000) {
strcpy(memo[memoCount++], stateKey);
}
// Try each ball type
char colors[] = {'R', 'Y', 'B', 'G', 'W'};
for (int c = 0; c < 5; c++) {
char* pos = strchr(curr.hand, colors[c]);
if (pos != NULL) {
// Remove one ball of this color from hand
char newHand[MAX_STATE_LEN];
strcpy(newHand, curr.hand);
char* removePos = strchr(newHand, colors[c]);
memmove(removePos, removePos + 1, strlen(removePos));
int posCount;
int* positions = getStrategicPositions(curr.board, &posCount);
for (int p = 0; p < posCount; p++) {
int insertPos = positions[p];
if (insertPos <= strlen(curr.board)) {
char newBoard[MAX_STATE_LEN];
strncpy(newBoard, curr.board, insertPos);
newBoard[insertPos] = colors[c];
strcpy(newBoard + insertPos + 1, curr.board + insertPos);
removeConsecutive(newBoard);
State newState;
strcpy(newState.board, newBoard);
strcpy(newState.hand, newHand);
newState.moves = curr.moves + 1;
enqueue(&queue, newState);
}
}
free(positions);
}
}
}
return -1;
}
Time & Space Complexity
Time Complexity
โฑ๏ธ
O(4^n * m)
Where n is the maximum depth (moves), m is board length for processing. Pruned by memoization.
n
2n
โ Linear Growth
Space Complexity
O(4^n * m)
BFS queue and memoization storage for unique states
n
2n
โก Linearithmic Space
Constraints
board and hand have lengths in range [1, 16]
Each ball color is one of 'R', 'Y', 'B', 'G', or 'W'
The input strings contain only the specified ball colors
Game rule: Groups of 3 or more consecutive same-colored balls are removed
Objective: Clear all balls using minimum insertions from hand
28.4K Views
MediumFrequency
~35 minAvg. Time
876 Likes
Ln 1, Col 1
Smart Actions
๐กExplanation
AI Ready
๐ก SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom โข Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
๐ก
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
๐ง
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
๐ก
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
๐ฌ
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
๐ง
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
๐ก
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
๐งช
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
๐
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
โก
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
๐ป
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
๐ฌ
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
๐ก
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.