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 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.

Input & Output

Example 1 — Basic Clear
$ Input: board = "RWWWRR", hand = "RB"
Output: 2
💡 Note: Insert B at position 1: RBWWWRR → RBWWWRR (no removal). Insert B at position 2: RBBWWWRR → R___WWWRR (BBB removed) → RWWWRR. Insert R at position 3: RWWRRRR → RWW___ (RRR removed) → RWW. Continue to clear remaining.
Example 2 — Impossible Case
$ Input: board = "RWWWRR", hand = "WWBBRR"
Output: -1
💡 Note: No matter how we insert the balls, we cannot clear all balls from the board with the given hand.
Example 3 — Already Clear
$ Input: board = "", hand = "RWB"
Output: 0
💡 Note: Board is already empty, so no moves needed.

Constraints

  • 1 ≤ board.length ≤ 16
  • 0 ≤ hand.length ≤ 5
  • board and hand consist of 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

Visualization

Tap to expand
Zuma Game: Clear All Balls with Minimum MovesInitial Board:RWWWRRHand:RBMove 1: Insert BRBWWWRRMove 2: Insert R→ Creates RRR groupRBWWWRRRResult: 2 moves needed to clear the board
Understanding the Visualization
1
Input
Board: RWWWRR, Hand: RB
2
Strategic Insertions
Insert balls to create groups of 3+ for removal
3
Chain Reactions
Removals can trigger cascading eliminations
4
Output
Minimum moves needed: 2
Key Takeaway
🎯 Key Insight: Use BFS with memoization to find the minimum sequence of insertions that creates chain reactions to clear the entire board
Asked in
Google 12 Microsoft 8 Apple 6
28.4K Views
Medium Frequency
~35 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen