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
.
n
always a positive integer?
n
is a positive integer.n
be extremely large?
n
can be large, but the solution should efficiently handle it.The main insight is to recognize the pattern of winning or losing based on the number of stones:
n
is 1, 2, or 3, you can take all the stones and win.n
is 4, no matter how many stones (1, 2, or 3) you take, your opponent will always be left with a winning position (1, 2, or 3 stones).n = 4
, you will always lose if both play optimally.When n > 4
, you can observe the following pattern repeating:
n % 4 == 0
leads to a losing position as any move leaves your opponent in a winning position.Based on this, the solution can be derived as:
true
if n % 4 != 0
, otherwise false
.def canWinNim(n: int) -> bool:
return n % 4 != 0
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.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?