#488

Zuma Game

Hard
StringDynamic ProgrammingStackBreadth-First SearchMemoizationDepth-First SearchMemoizationBacktracking
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m²)
Space
O(1)
O(n * m)
💡

Intuition

Time O(n * m²)Space O(n * m)

The optimal solution uses a depth-first search (DFS) combined with memoization to efficiently explore the possible placements of balls while avoiding redundant calculations. It minimizes the number of balls needed by leveraging the hand's available balls strategically.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a function to remove consecutive balls from the board.
  2. 2Step 2: Use a recursive DFS function to explore all possible placements of balls from the hand.
  3. 3Step 3: Use memoization to store results of previously computed states to avoid recalculating.
solution.py36 lines
1def findMinStep(board, hand):
2    from collections import Counter
3    hand_count = Counter(hand)
4    memo = {}
5    def remove_consecutive(b):
6        i = 0
7        while i < len(b):
8            j = i
9            while j < len(b) and b[j] == b[i]:
10                j += 1
11            if j - i >= 3:
12                return remove_consecutive(b[:i] + b[j:])
13            i = j
14        return b
15    def dfs(b, hand_count):
16        if (b, tuple(hand_count.items())) in memo:
17            return memo[(b, tuple(hand_count.items()))]
18        b = remove_consecutive(b)
19        if not b:
20            return 0
21        if not hand_count:
22            return float('inf')
23        min_steps = float('inf')
24        for i in range(len(b) + 1):
25            for color in hand_count:
26                if hand_count[color] > 0:
27                    hand_count[color] -= 1
28                    new_board = b[:i] + color + b[i:]
29                    steps = dfs(new_board, hand_count)
30                    if steps != float('inf'):
31                        min_steps = min(min_steps, steps + 1)
32                    hand_count[color] += 1
33        memo[(b, tuple(hand_count.items()))] = min_steps
34        return min_steps
35    result = dfs(board, hand_count)
36    return result if result != float('inf') else -1

Complexity note: The time complexity is O(n * m²) where n is the length of the board and m is the number of distinct colors in hand. This is due to the recursive nature of the DFS and the memoization storing results for each unique state.

  • 1Understanding how to remove consecutive elements is crucial.
  • 2Memoization can significantly reduce redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.