1252. Grundy Number and Sprague-Grundy Theorem

HardDynamic ProgrammingGame Theory

In a subtraction game, a pile of n stones allows a move that removes exactly m stones for any m in the given moves set. Compute the Grundy number of the pile of size n, defined recursively as the smallest non-negative integer not among the Grundy numbers of the reachable positions. The input is JSON {n, moves}.

Input: JSON {n, moves}.

Output: Integer — the Grundy number of the position.

Examples

Example 1
Input: {"n":5,"moves":[1,2,3]}
Output: 1
Explanation: Grundy values cycle with period 4.
Example 2
Input: {"n":4,"moves":[1,2]}
Output: 1
Explanation: Period-3 cycle.
Example 3
Input: {"n":0,"moves":[1]}
Output: 0
Explanation: No moves available.

Constraints

Asked by

AmazonGoogleMicrosoftMetaAdobe
Solve this problem in the editor →