KatInterview

488. Zuma Game

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the minimum number of balls from our hand to insert into a row of balls on a board to clear the entire board. An insertion can trigger a chain reaction of removals: if a group of three or more same-colored balls forms, it's removed. This removal might bring other balls of the same color together, forming new groups of three or more, which are also removed. This continues until no such groups exist.

Solution

Zuma Game in Python

class Solution:
    def findMinStep(self, board: str, hand: str) -> int:
        hand_sorted = "".join(sorted(hand))
        # Memoization dictionary: (board, hand) -> min_steps
        self.memo = {}
        
        result = self.solve(board, hand_sorted)
        
        return result if result <= len(hand) else -1

    def update(self, board: str) -> str:
        # Repeatedly remove groups of 3 or more
        start = 0
        while start < len(board):
            end = start
            while end < len(board) and board[start] == board[end]:
                end += 1
            
            if end - start >= 3:
                board = board[:start] + board[end:]
                start = 0 # Restart scan
            else:
                start += 1
        return board

    def solve(self, board: str, hand: str) -> int:
        if not board:
            return 0
        if not hand:
            return float('inf')
        
        state = (board, hand)
        if state in self.memo:
            return self.memo[state]
        
        min_balls = float('inf')

        # Iterate through each ball in hand
        i = 0
        while i < len(hand):
            ball_in_hand = hand[i]

            # Iterate through each possible insertion position on the board
            for j in range(len(board) + 1):
                # Pruning: Don't insert a ball 'C' right after another 'C'.
                if j > 0 and board[j - 1] == ball_in_hand:
                    continue

                new_board = board[:j] + ball_in_hand + board[j:]
                updated_board = self.update(new_board)
                
                new_hand = hand[:i] + hand[i+1:]
                
                result = self.solve(updated_board, new_hand)
                
                if result != float('inf'):
                    min_balls = min(min_balls, 1 + result)
            
            # Pruning: Skip duplicate balls in hand
            while i < len(hand) and hand[i] == ball_in_hand:
                i += 1

        self.memo[state] = min_balls
        return min_balls

Zuma Game in Java

class Solution {
    private Map<String, Integer> memo = new HashMap<>();
    private final int MAX_MOVES = 6; // A value > hand.length()

    public int findMinStep(String board, String hand) {
        char[] handChars = hand.toCharArray();
        Arrays.sort(handChars);
        int result = solve(board, new String(handChars));
        return result == MAX_MOVES ? -1 : result;
    }

    private int solve(String board, String hand) {
        if (board.isEmpty()) {
            return 0;
        }
        if (hand.isEmpty()) {
            return MAX_MOVES;
        }

        String key = board + "#" + hand;
        if (memo.containsKey(key)) {
            return memo.get(key);
        }

        int minBalls = MAX_MOVES;

        // Iterate through each ball in hand
        for (int i = 0; i < hand.length(); i++) {
            // Pruning: skip duplicate balls in hand to avoid redundant computations
            if (i > 0 && hand.charAt(i) == hand.charAt(i - 1)) {
                continue;
            }

            char ballInHand = hand.charAt(i);

            // Iterate through each possible insertion position on the board
            for (int j = 0; j <= board.length(); j++) {
                // Pruning: Don't insert a ball 'C' right after another 'C'.
                if (j > 0 && board.charAt(j - 1) == ballInHand) {
                    continue;
                }

                StringBuilder newBoardSb = new StringBuilder(board);
                newBoardSb.insert(j, ballInHand);
                String updatedBoard = update(newBoardSb.toString());

                String newHand = hand.substring(0, i) + hand.substring(i + 1);

                int result = solve(updatedBoard, newHand);

                if (result < MAX_MOVES) {
                    minBalls = Math.min(minBalls, 1 + result);
                }
            }
        }

        memo.put(key, minBalls);
        return minBalls;
    }

    // Helper function to update the board according to Zuma rules.
    private String update(String board) {
        int start = 0;
        while (start < board.length()) {
            int end = start;
            while (end < board.length() && board.charAt(start) == board.charAt(end)) {
                end++;
            }
            if (end - start >= 3) {
                board = board.substring(0, start) + board.substring(end);
                start = 0; // Restart scan from the beginning
            } else {
                start++;
            }
        }
        return board;
    }
}

Zuma Game in C++

class Solution {
public:
    int findMinStep(string board, string hand) {
        sort(hand.begin(), hand.end());
        int result = solve(board, hand);
        return result > hand.length() ? -1 : result;
    }

private:
    map<string, int> memo;

    // Recursive solver with memoization
    int solve(string board, string hand) {
        if (board.empty()) {
            return 0;
        }
        if (hand.empty()) {
            return 6; // Impossible, use a value > hand.length()
        }
        
        string key = board + "#" + hand;
        if (memo.count(key)) {
            return memo[key];
        }

        int min_balls = 6; // Initialize with a value > max possible hand size

        // Iterate through each ball in hand
        for (int i = 0; i < hand.length(); ++i) {
            // Pruning: if hand has duplicates, e.g., "RRG", only process the first 'R'
            // for this level. The second 'R' will be available in subsequent recursive calls.
            if (i > 0 && hand[i] == hand[i-1]) {
                continue;
            }

            // Iterate through each possible insertion position on the board
            for (int j = 0; j <= board.length(); ++j) {
                // Pruning: Don't insert a ball 'C' right after another 'C'.
                // For example, if board is "R" and hand has "R", inserting at j=0 gives "RR".
                // Inserting at j=1 also gives "RR". This pruning avoids the duplicate work.
                if (j > 0 && board[j - 1] == hand[i]) {
                    continue;
                }

                string new_board = board.substr(0, j) + hand[i] + board.substr(j);
                string updated_board = update(new_board);
                
                string new_hand = hand.substr(0, i) + hand.substr(i+1);
                
                int result = solve(updated_board, new_hand);
                
                if (result < 6) { // If subproblem is solvable
                    min_balls = min(min_balls, 1 + result);
                }
            }
        }

        return memo[key] = min_balls;
    }

    // Helper function to apply the Zuma rule and update the board, handling chain reactions.
    string update(string board) {
        int start = 0;
        while(start < board.length()) {
            int end = start;
            while(end < board.length() && board[start] == board[end]) {
                end++;
            }
            if (end - start >= 3) {
                board.erase(start, end - start);
                start = 0; // Restart scan from the beginning
            } else {
                start++;
            }
        }
        return board;
    }
};

Zuma Game in TypeScript

function findMinStep(board: string, hand: string): number {
    const memo = new Map<string, number>();
    const MAX_MOVES = 6; // A value > hand.length()

    const sortedHand = hand.split('').sort().join('');

    function update(board: string): string {
        let start = 0;
        while (start < board.length) {
            let end = start;
            while (end < board.length && board[start] === board[end]) {
                end++;
            }
            if (end - start >= 3) {
                board = board.substring(0, start) + board.substring(end);
                start = 0; // Restart scan from the beginning
            } else {
                start++;
            }
        }
        return board;
    }

    function solve(board: string, hand: string): number {
        if (board.length === 0) {
            return 0;
        }
        if (hand.length === 0) {
            return MAX_MOVES;
        }

        const key = `${board}#${hand}`;
        if (memo.has(key)) {
            return memo.get(key)!;
        }

        let minBalls = MAX_MOVES;

        // Iterate through each ball in hand
        for (let i = 0; i < hand.length; i++) {
            // Pruning: skip duplicate balls in hand to avoid redundant computations
            if (i > 0 && hand[i] === hand[i - 1]) {
                continue;
            }

            const ballInHand = hand[i];

            // Iterate through each possible insertion position on the board
            for (let j = 0; j <= board.length; j++) {
                // Pruning: Don't insert a ball 'C' right after another 'C'.
                if (j > 0 && board[j - 1] === ballInHand) {
                    continue;
                }

                const newBoard = board.substring(0, j) + ballInHand + board.substring(j);
                const updatedBoard = update(newBoard);

                const newHand = hand.substring(0, i) + hand.substring(i + 1);

                const result = solve(updatedBoard, newHand);

                if (result < MAX_MOVES) {
                    minBalls = Math.min(minBalls, 1 + result);
                }
            }
        }

        memo.set(key, minBalls);
        return minBalls;
    }

    const result = solve(board, sortedHand);
    return result === MAX_MOVES ? -1 : result;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.