# Leetcode – Nim Game

Tags: LeetCodeYou are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.

Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.

For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.

**Hint:**

- If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?

**Analysis**

A native method is to use deep first search. The basic ideas can be expressed as:

1 2 3 4 5 6 7 8 9 |
boolean canWin(int n){ if (n <= 3) return true; if (n == 4) return false; //I can choose a solution to make my friend fail boolean friendWin = canWin(n - 1) && canWin(n - 2) && canWin(n - 3); //my friend fail == my win return !friendWin; } |

We can make the above program faster using dynamic programming.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
boolean canWin(int n) { Map<Integer, Boolean> res = new HashMap<>(); int i = 1; while(i <= n) { if (i <= 3) { res.put(i, true); i++; continue; } if(i == 4) { res.put(i, false); i++; continue; } // find one solution that let friend fail after a choose boolean counter = res.get(i - 1) && res.get(i - 2) && res.get(i - 3); res.put(i, !counter); i++; } return res.get(n); } |

The above solutions can not work for large n. It turned out that, the first player will loose only when` n % 4 == 0`

.

- n = 1, 2, 3, the first player wins
- n == 4, the first play looses no matter what he will choose, his friend will have n <=3, win!
- n == 5, the first player can pick 1, thus leave his friend with 4, the friend will loose!
- n == 6, the first player can pick 2, thus leave his friend with 4.
- n == 7, the first player can pick 3, thus leave his friend with 7.
- n == 8, the first player will leave his friend with 7, 6 or 5. So his friend will win!
- n == 9, the first player will pick 1, so leave his friend with 8, his friend will loose.

So the final solution can be easily implemented in Java as follows:

1 2 3 4 5 6 7 |
boolean canWin(int n) { if (n%4 == 0) { return false; } return true; } |