Skip to content
We areTOP 1%
DSA · Competitive Programmer · Pattern 8 of 9

Game Theory

9 problems.
Your progress0%
1st Visit
0/9
2nd Visit
0/9
Revise
0/9

About this pattern

In an impartial game both players have the same moves, and under normal play the player who cannot move loses. Classify positions backwards: a position is winning if some move reaches a losing position, and losing if every move reaches a winning one. Brute-forcing small cases often reveals a periodic pattern that can be proved afterwards. When a game splits into independent parts, the Sprague-Grundy theorem assigns each part a Grundy number, the minimum excluded value among its options, and the whole position is losing exactly when the XOR of those numbers is zero. Score-based games instead use minimax DP on the difference between the two players' totals.

// Grundy numbers of one pile when a move removes any amount listed in moves
vector<int> grundy(int maxN, const vector<int>& moves) {
    vector<int> g(maxN + 1, 0);
    for (int n = 1; n <= maxN; n++) {
        vector<bool> seen(moves.size() + 2, false);
        for (int m : moves)
            if (m <= n && g[n - m] < (int)seen.size()) seen[g[n - m]] = true;
        while (seen[g[n]]) g[n]++;            // mex of the reachable values
    }
    return g;
}
// A sum of independent piles is losing iff the XOR of g[pile] is 0

Problems

Game Theory questions
#ProblemPlatformDifficultyOpen1st1st Visit2nd2nd VisitRevRevise
1Stone Game IIILeetCodeHard Solve Stone Game III on LeetCode (opens in a new tab)
21-2-K GameCodeforcesMedium 1700Solve 1-2-K Game on Codeforces (opens in a new tab)
3Stoned GameCodeforcesHard 1800Solve Stoned Game on Codeforces (opens in a new tab)
4A Lot of GamesCodeforcesHard 1900Solve A Lot of Games on Codeforces (opens in a new tab)
5GameGameCodeforcesHard 1900Solve GameGame on Codeforces (opens in a new tab)
6Tree TagCodeforcesHard 1900Solve Tree Tag on Codeforces (opens in a new tab)
7Cat and MouseLeetCodeHard Solve Cat and Mouse on LeetCode (opens in a new tab)
8Not a Nim ProblemCodeforcesHard 2100Solve Not a Nim Problem on Codeforces (opens in a new tab)
9Lieges of LegendreCodeforcesHard 2200Solve Lieges of Legendre on Codeforces (opens in a new tab)

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account