Description

You have a row of colored balls on a board. You have balls in your hand to insert. Remove all balls on the board by inserting balls to make 3+ consecutive same-colored balls disappear. Return minimum insertions needed, or -1 if impossible.

Examples

Input:board = "WRRBBW", hand = "RB"
Output:-1
Explanation:

Cannot remove all balls.

Input:board = "a", hand = "a"
Output:0
Explanation:

Edge case with a single character.

Input:board = "RWWWRR", hand = "R"
Output:1
Explanation:

Inserting one 'R' at position 0 makes 'RRWWWRR'. The 3 consecutive R's at the beginning are removed, leaving 'WWWRR'. The 3 consecutive W's are then removed, leaving 'RR'. One more 'R' insertion would clear the board, but the minimum insertions for this input is 2.

Constraints

  • 1 ≤ board.length ≤ 16
  • 1 ≤ hand.length ≤ 5

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!