algoadvance

Leetcode 1025. Divisor Game

Problem Statement

Alice and Bob take turns playing a game, with Alice starting first.

Initially, there is a number N on the chalkboard. On each player’s turn, that player makes a move consisting of:

  1. Choosing any x with 0 < x < N and N % x == 0.
  2. Replacing the number N on the chalkboard with N - x.

Also, if a player cannot make a move, they lose the game.

Return true if and only if Alice wins the game, assuming both players play optimally.


Clarifying Questions

  1. Are there any constraints on the value of N?
    • Yes. Typically, 1 <= N <= 1000.
  2. Should we account for any specific input verification or can we assume the input is always valid?
    • We can assume the input is always valid as per usual LeetCode problem constraints.

Strategy

To determine whether Alice wins given she starts first, we can consider the parity of N:

  1. If N is even:
    • Alice can always choose x=1, which would make N an odd number for Bob’s turn.
    • An odd number always has at least one divisor 1, and following this strategy, Bob would eventually have to deal with an even number, switching back to Alice in a better position.
    • Thus, Alice can always maintain a winning position by forcing Bob to play an odd N.
  2. If N is odd:
    • Any move Alice makes would result in Bob dealing with an even number (since subtracting an odd number from an odd number results in an even number).
    • Given the same strategy, Bob can always ensure Alice faces an odd number in subsequent turns until Alice loses.

This pattern suggests that Alice wins if and only if N is even.


Code

Here is the implementation following the described strategy:

class Solution {
public:
    bool divisorGame(int N) {
        return N % 2 == 0;
    }
};

Time Complexity

The time complexity of this solution is:

This solution effectively utilizes the observation about even and odd numbers in this specific game context, ensuring optimal performance.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI