algoadvance

Leetcode 292. Nim Game

Problem Statement

You are playing the following Nim Game with your friend:

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

Clarifying Questions

  1. Boundary Conditions:
    • Can n be zero or negative, or should n always be a positive integer?
      • For this problem, it’s assumed that n is a positive integer as specified by the problem constraints in competitive programming platforms.
  2. Optimal Play:
    • Both players always play optimally. Do you need to account for any sub-optimal moves?
      • No, both players will always make the best possible moves.

Strategy

The key insight for solving this problem is recognizing the pattern of winning and losing positions:

Therefore, we observe that if n % 4 == 0, you will lose; otherwise, you will win.

Code

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

Time Complexity

The time complexity of this solution is O(1) since the operation of taking the modulus and comparing it to a constant involves a constant amount of work, regardless of the input size.

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