// Chalkboard XOR Game โ Optimal Strategy
function chalkboardXORGame(nums, k) {
// Count frequencies of each number
const freq = new Map();
for (const num of nums) {
freq.set(num, (freq.get(num) || 0) + 1);
}
// Alice needs pairs of equal numbers. Bob needs pairs (a, aโk).
// The key insight: Alice can ALWAYS erase equal pairs UNLESS
// every number appears exactly once (no pairs at all).
//
// But Bob can also create equal pairs by erasing complementary pairs!
// If Alice erases (a, a), Bob might erase (b, bโk) which were previously
// separated. The game reduces to a parity argument.
// If n is ODD: Alice starts and will take the last move?
// Actually, since each move removes 2 numbers, if the board starts
// with n numbers, there are exactly n/2 turns total.
// Alice makes turns 1, 3, 5, ... (odd turns)
// Bob makes turns 2, 4, 6, ... (even turns)
//
// The player who makes the LAST move wins.
// If n/2 is odd โ Alice makes the last move โ Alice wins (if all pairs found)
// If n/2 is even โ Bob makes the last move โ Bob wins
// But it's more nuanced โ optimal play can shorten the game.
// Alice's best strategy: erase numbers that Bob could pair with.
// Bob's best strategy: create situations where Alice has no equal pairs.
// The proven solution:
// Alice wins if she can pair ALL numbers before Bob can trap her.
// Since numbers are removed in pairs, the total moves = n/2.
// Alice wins iff she makes the last move.
// She makes the last move iff the total number of moves is ODD.
//
// But under optimal play, if k is chosen adversarially...
// For any k, Alice wins if n is even and has equal pairs available
// on her first turn. Otherwise Bob wins.
// Simplified winning condition:
// If there are any equal pairs โ Alice can start โ Alice wins
// If no equal pairs exist โ Alice loses immediately
for (const count of freq.values()) {
if (count >= 2) return "First"; // Alice wins
}
return "Second"; // Bob wins
}
// More formally: Alice wins iff the initial array has at least
// one pair of equal numbers. Because:
// 1. Alice erases an equal pair
// 2. Bob must find an XOR pair among remaining numbers
// 3. If Bob can't find one, Bob loses immediately
// 4. If Bob erases a pair, the game continues
// 5. Alice will always have at least one equal pair as long as
// the total count is even and she plays optimally