algoadvance

You are playing the following Nim Game with your friend:

Given an integer n, representing 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. Is n always a positive integer?
    • Yes, it’s guaranteed that n is a positive integer.
  2. Can n be extremely large?
    • The value of n can be large, but the solution should efficiently handle it.

Strategy:

The main insight is to recognize the pattern of winning or losing based on the number of stones:

When n > 4, you can observe the following pattern repeating:

Based on this, the solution can be derived as:

Code:

def canWinNim(n: int) -> bool:
    return n % 4 != 0

Time Complexity:

By leveraging the nature of divisibility and modular arithmetic, we can determine the winning or losing position for any number of stones in constant time.

Try our interview co-pilot at AlgoAdvance.com