↓Skip to main content
  1. LeetCode/

LeetCode 1025: Divisor Game

·2 mins· ·
LeetCode Easy Math Dynamic-Programming Brainteaser 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-09-27

  • Submissions: Accepted ×2 → Runtime Error ×2 → Wrong Answer → Accepted ×3

Approach
#

Game DP: dp[i] says whether the player facing i wins, true when some x | i with x < i makes dp[i - x] false (the opponent loses). Running it shows dp[i] is exactly “i is even” (Linear DP, “tagged DP but an observation is faster”): from an even number take 1, leaving the opponent odd; an odd number has only odd divisors, so any move leaves the opponent even.

My Attempts
#

In 2022-09 n % 2 == 0 passed at once. In 2022-11 I practiced the DP version:

  • It started with [False] * len(n) (an integer has no length), then an index out of range.
  • After that the outer loop was range(n), so dp[n] itself was never computed and stayed False: n = 2 returned False. range(n + 1) passed.

Solution
#

class Solution:
    def divisorGame(self, n: int) -> bool:
        return n % 2 == 0

Complexity
#

Time O(1), space O(1); the DP version is O(n²).

Mistakes to Avoid
#

  • The DP loop must include n itself: range(n + 1).
  • The array length is n + 1, not len(n).

Interview Explanation
#

A DP works, with dp[i] true when some divisor x leaves the opponent losing at i - x; but an even number can take 1 to hand over an odd one, and an odd number’s divisors are all odd so it must hand over an even one, so the answer is whether n is even.

Related

LeetCode 292: Nim Game
·1 min
LeetCode Easy Math Brainteaser Minimax-Algorithm Game-Theory
LeetCode 292 note: whoever faces a multiple of 4 stones loses, so the first player wins when n % 4 != 0
LeetCode 509: Fibonacci Number
·1 min
LeetCode Easy Math Dynamic-Programming Recursion Memoization
LeetCode 509 note: the starting point of 1D DP; only the previous two terms are needed, so roll two variables
LeetCode 989: Add to Array-Form of Integer
·2 mins
LeetCode Easy Array Math
LeetCode 989 note: treat k as the carry, add from the last element backwards, and keep prepending digits while k remains
LeetCode 908: Smallest Range I
·1 min
LeetCode Easy Array Math
LeetCode 908 note: lower the maximum by k and raise the minimum by k; the answer is max(0, max - min - 2k)
LeetCode 914: X of a Kind in a Deck of Cards
·2 mins
LeetCode Easy Array Hash-Table Math Counting
LeetCode 914 note: every card count must be divisible by one X >= 2, i.e. the GCD of all counts is at least 2
LeetCode 892: Surface Area of 3D Shapes
·2 mins
LeetCode Easy Array Math Geometry Matrix
LeetCode 892 note: a stack of v cubes has 4v + 2 faces; subtract 2 × min for each overlap with the stacks above and to the left