↓Skip to main content
  1. LeetCode/

LeetCode 292: Nim Game

·1 min· ·
LeetCode Easy Math Brainteaser Minimax-Algorithm Game-Theory
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-23

  • Submissions: Accepted (first try)

Approach
#

Look at small cases first (Math Template 4): with 1 to 3 stones you take them all and win; with 4, any move leaves the opponent 1 to 3, so you lose. In general, facing a multiple of 4, whatever x you take the opponent takes 4 - x, keeping you on multiples of 4; otherwise you can take enough to leave the opponent on one.

My Solution
#

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

Complexity
#

Time O(1), space O(1).

Mistakes to Avoid
#

  • n reaches 2^31, too large for DP in time or memory; find the pattern.

Interview Explanation
#

Small cases show that facing a multiple of 4 loses, since the opponent can always make each round total 4, so the first player wins exactly when n is not a multiple of 4. Time O(1).

Related

LeetCode 263: Ugly Number
·1 min
LeetCode Easy Math
LeetCode 263 note: only positive numbers can be ugly; divide out every factor 2, 3 and 5 and check whether 1 remains
LeetCode 326: Power of Three
·1 min
LeetCode Easy Math Recursion
LeetCode 326 note: divide by 3 while possible and check for 1; without loops, n is a power of three exactly when it divides 3^19
LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0
LeetCode 342: Power of Four
·1 min
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 342 note: confirm a power of two, then that the single 1 sits at an even position: n & 0x55555555 != 0, or n % 3 == 1
LeetCode 367: Valid Perfect Square
·1 min
LeetCode Easy Math Binary-Search
LeetCode 367 note: binary search [1, num] for mid² == num without using sqrt
LeetCode 405: Convert a Number to Hexadecimal
·2 mins
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 note: add 2^32 to a negative number to get its two’s complement, then take 4 bits at a time (% 16); handle 0 separately