Coin game winner where every player has three choices

Pattern: 1D DP

medium

With n coins, a move takes 1, x or y coins and whoever takes the last coin wins. A position is winning when some move leads to a losing position for the other player. Fill this from 0 coins (a loss for the player to move) upwards.

The problem

Two players take turns removing 1, x or y coins from a pile of n; the one who takes the last coin wins. Player A moves first. Return whether A wins with perfect play. n = 5, x = 3, y = 4 is true. GFG prints the winner's letter; this guide returns whether the first player wins.

Think first

  • With 0 coins left, who has lost?
  • When is a position winning?
  • In what order can positions be decided?

Hints

    Brute force, and why it fails

    Game-tree search without memory: exponential.

    The key insight

    Each position's result depends only on three smaller positions.

    Dry run

    winF T F

    x = 3, y = 4. win[0] = false. win[1] = true (take 1), win[2] = false.

    Step 1 of 2

    The plan

    win[0] = false
    for m: win[m] = not win[m-1] or (m >= x and not win[m-x]) or (m >= y and not win[m-y])
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    Three checks per position.

    Edge cases

    • n smaller than x and y.
    • x = y.
    • n = 1: true.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean findWinner(int n, int x, int y) {
            boolean[] win = new boolean[n + 1];     // win[m]: the player to move wins with m coins left
            for (int m = 1; m <= n; m++)            // win if some move leaves the other player in a losing position
                win[m] = !win[m - 1] || (m >= x && !win[m - x]) || (m >= y && !win[m - y]);
            return win[n];
        }
    }

    C++

    class Solution {
    public:
        bool findWinner(int n, int x, int y) {
            vector<bool> win(n + 1, false);         // win[m]: the player to move wins with m coins left
            for (int m = 1; m <= n; m++)            // win if some move leaves the other player in a losing position
                win[m] = !win[m - 1] || (m >= x && !win[m - x]) || (m >= y && !win[m - y]);
            return win[n];
        }
    };

    Python

    class Solution:
        def findWinner(self, n: int, x: int, y: int) -> bool:
            win = [False] * (n + 1)                 # win[m]: the player to move wins with m coins left
            for m in range(1, n + 1):               # win if some move leaves the other player in a losing position
                win[m] = (not win[m - 1]) or (m >= x and not win[m - x]) or (m >= y and not win[m - y])
            return win[n]

    Common mistakes

    • Thinking 'win' means taking the most coins.
    • Allowing moves larger than the pile.

    Similar problems