Skip to main content
Back to problems
#1908
Medium Algorithms

Game of nim

Array Math Dynamic Programming Bit Manipulation Brainteaser Game Theory
63.0% acceptance
Mar 31, 2026
104
40
Alice and Bob take turns playing a game with Alice starting first. In this game, there are n piles of stones. On each player's turn, the player should remove any positive number of stones from a non-empty pile of his or her choice. The first player who cannot make a move loses, and the other player wins. Given an integer array piles, where piles[i] is the number of stones in the ith pile, return true if Alice wins, or false if Bob wins. Both Alice and Bob play optimally.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn nim_game(piles: Vec<i32>) -> bool {
    piles.iter().fold(0, |acc, &x| acc ^ x) != 0
  }
}