1468. Two-Pile Queen Duel

Hard7.5 points estimatedGame TheoryMathsBrainteaser

Two players sit at a token table holding two heaps of coins, with a coins in the first heap and b coins in the second. They alternate turns, and the first player moves first. On a turn a player must either remove any positive number of coins from exactly one heap, or remove the same positive number of coins from both heaps at once. Whoever removes the last coin wins; a player who faces two empty heaps has already lost. Both players play perfectly. Return true if the first player wins and false otherwise. The answer must be computed in O(1) time and O(1) space, so the heaps may be far too large for any table-based search.

Example 1

Input:
a = 0, b = 0
Output:
false
Explanation:

There are no coins, so the first player cannot move and loses.

Example 2

Input:
a = 1, b = 2
Output:
false
Explanation:

Every move from (1, 2) leaves the opponent a winning position, so the first player loses.

Example 3

Input:
a = 3, b = 4
Output:
true
Explanation:

Removing 2 coins from both heaps leaves (1, 2), which is a losing position for the opponent, so the first player wins.

Constraints

0 ≤ a, b ≤ 107

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 600 msC++ 150 msJava 300 msJavaScript 300 msTypeScript 300 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…