294. Flip Game II
MediumSolutions 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 describes a game played with a string of '+' and '-' characters. This is an impartial game, meaning the available moves depend only on the state of the game, not on which player is moving. Such games can often be analyzed using combinatorial game theory, particularly the Sprague-Grundy theorem.
Solution
Flip Game II in Python
class Solution:
# Precompute Grundy numbers as a class attribute.
# This is done once when the Solution class is defined.
_g = [0] * 61
for k in range(2, 61):
seen_grundy_values = set()
# A move on k '+'s splits it into two sub-games of i and k-2-i '+'s.
# The Grundy value of the resulting position is g[i] ^ g[k-2-i].
for i in range((k - 2) // 2 + 1):
seen_grundy_values.add(_g[i] ^ _g[k - 2 - i])
# Find the Minimum Excluded value (mex).
mex = 0
while mex in seen_grundy_values:
mex += 1
_g[k] = mex
def canWin(self, currentState: str) -> bool:
# Split the string by '-' to get blocks of consecutive '+'s.
plus_blocks = currentState.split('-')
nim_sum = 0
# For each block, XOR its Grundy value into the nim_sum.
for block in plus_blocks:
length = len(block)
if length > 0:
nim_sum ^= self._g[length]
# A position is a winning position if and only if its nim-sum is non-zero.
return nim_sum != 0
Flip Game II in Java
class Solution {
// Precompute Grundy numbers for games on k consecutive '+'s.
// Using a static block ensures this is done only once when the class is loaded.
private static int[] g = new int[61];
static {
for (int k = 2; k <= 60; k++) {
HashSet<Integer> seenGrundyValues = new HashSet<>();
// A move on k '+'s splits it into two sub-games of i and k-2-i '+'s.
// The Grundy value of the resulting position is g[i] ^ g[k - 2 - i].
for (int i = 0; i <= (k - 2) / 2; i++) {
seenGrundyValues.add(g[i] ^ g[k - 2 - i]);
}
// Find the Minimum Excluded value (mex).
int mex = 0;
while (seenGrundyValues.contains(mex)) {
mex++;
}
g[k] = mex;
}
}
public boolean canWin(String currentState) {
int nimSum = 0;
int currentLen = 0;
// Parse the string to find blocks of '+' and compute the nim-sum.
for (int i = 0; i < currentState.length(); i++) {
if (currentState.charAt(i) == '+') {
currentLen++;
} else {
if (currentLen > 0) {
nimSum ^= g[currentLen];
}
currentLen = 0;
}
}
// Handle the last block if the string ends with '+'.
if (currentLen > 0) {
nimSum ^= g[currentLen];
}
// A position is a winning position if and only if its nim-sum is non-zero.
return nimSum != 0;
}
}
Flip Game II in C++
class Solution {
public:
bool canWin(string currentState) {
// Precompute Grundy numbers for games on k consecutive '+'s.
// This is done once using a static variable with a lambda initializer.
static vector<int> g = [](){
vector<int> g(61, 0);
for (int k = 2; k <= 60; ++k) {
unordered_set<int> seen_grundy_values;
// A move on k '+'s splits it into two sub-games of i and k-2-i '+'s.
// The Grundy value of the resulting position is g[i] ^ g[k - 2 - i].
for (int i = 0; i <= (k - 2) / 2; ++i) {
seen_grundy_values.insert(g[i] ^ g[k - 2 - i]);
}
// Find the Minimum Excluded value (mex).
int mex = 0;
while (seen_grundy_values.count(mex)) {
mex++;
}
g[k] = mex;
}
return g;
}();
int nim_sum = 0;
int current_len = 0;
// Parse the string to find blocks of '+' and compute the nim-sum.
for (char c : currentState) {
if (c == '+') {
current_len++;
} else {
if (current_len > 0) {
nim_sum ^= g[current_len];
}
current_len = 0;
}
}
// Handle the last block if the string ends with '+'.
if (current_len > 0) {
nim_sum ^= g[current_len];
}
// A position is a winning position if and only if its nim-sum is non-zero.
return nim_sum != 0;
}
};
Flip Game II in TypeScript
// Precompute Grundy numbers in the module scope. This runs once when the script is loaded.
const g: number[] = new Array(61).fill(0);
for (let k = 2; k <= 60; k++) {
const seenGrundyValues = new Set<number>();
// A move on k '+'s splits it into two sub-games of i and k-2-i '+'s.
// The Grundy value of the resulting position is g[i] ^ g[k-2-i].
for (let i = 0; i <= Math.floor((k - 2) / 2); i++) {
seenGrundyValues.add(g[i] ^ g[k - 2 - i]);
}
// Find the Minimum Excluded value (mex).
let mex = 0;
while (seenGrundyValues.has(mex)) {
mex++;
}
g[k] = mex;
}
function canWin(currentState: string): boolean {
// Split the string by '-' to get blocks of consecutive '+'s.
const plusBlocks = currentState.split('-');
let nimSum = 0;
// For each block, XOR its Grundy value into the nim_sum.
for (const block of plusBlocks) {
const length = block.length;
if (length > 0) {
nimSum ^= g[length];
}
}
// A position is a winning position if and only if its nim-sum is non-zero.
return nimSum !== 0;
};
More Medium LeetCode answers
- 95. Unique Binary Search Trees II
- 96. Unique Binary Search Trees
- 97. Interleaving String
- 99. Recover Binary Search Tree
- 102. Binary Tree Level Order Traversal
- 103. Binary Tree Zigzag Level Order Traversal
- 105. Construct Binary Tree from Preorder and Inorder Traversal
- 107. Binary Tree Level Order Traversal II
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.