1529. Misere Stone Duel

Easy1.5 points estimatedGame TheoryBrainteaserMaths

Two players share a single pile of n stones and move alternately, the first player starting. On a turn, the player must remove between 1 and m stones from the pile, both inclusive and never more than what remains. This game is played in reverse: the player who takes the very last stone loses. Both players play perfectly.

Return true if the first player can force a win, and false otherwise. With a pile of one stone the player to move is forced to take it and loses, which suggests thinking in blocks of m + 1 stones: the player who can always leave the opponent a pile whose size minus one is a multiple of m + 1 controls the game. Simulating the game is too slow for the given limits, so derive a direct formula. The solution runs in O(1) time and O(1) extra space.

Example 1

Input:
n = 1, m = 3
Output:
false
Explanation:

With a single stone the first player must take it and loses.

Example 2

Input:
n = 5, m = 2
Output:
true
Explanation:

The first player takes 1, leaving 4 stones; every reply lets the first player leave a pile of 1 for the opponent eventually, so the first player wins.

Constraints

1 ≤ n ≤ 109; 1 ≤ m ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(1)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…