algoadvance

Leetcode 292. Nim Game

Problem Statement:

You are playing the following Nim Game with your friend:

Given n, the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false.

Clarifying Questions:

  1. What is the smallest and largest size of the heap n that we can expect?
    • You can assume n is a positive integer, and reasonable constraints would be 1 <= n <= 2^31 - 1.
  2. If both players play optimally, does this mean they aim to win if possible?
    • Yes, both players will take their moves in an optimal manner to maximize their own chances of winning.

Strategy:

The problem can be solved using a bit of mathematical insight rather than a complex algorithm.

Observation:

From this basis, you can observe the following pattern:

Thus, the solution is simply to check if n is a multiple of 4.

Code:

public class Solution {
    public boolean canWinNim(int n) {
        return n % 4 != 0;
    }
}

Time Complexity:

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI