Magicsheet logo

Can I Win

Medium
56.3%
Updated 6/1/2025

Can I Win

What is this problem about?

The Can I Win interview question is a classic game theory problem. Two players take turns picking integers from 1 to maxChoosableInteger. Once an integer is picked, it cannot be used again. The player who first makes the total sum of picked integers >= desiredTotal wins. You need to determine if the first player can force a win, assuming both players play optimally. This Can I Win coding problem is a test of strategic lookahead and state management.

Why is this asked in interviews?

Companies like Uber, Meta, and Google use this to evaluate a candidate's mastery of recursion and state representation. Since the number of used integers can be represented as a bitmask, it tests your ability to use memoization to avoid exponential time complexity. It checks if you understand the minimax principle: a player wins if they can make a move that leaves the opponent in a state from which they cannot win.

Algorithmic pattern used

This utilizes the Math, Bitmask, Memoization, Game Theory, Dynamic Programming interview pattern.

  • State: A bitmask representing which integers have been used.
  • Recursion: For the current player, try every available integer. If choosing one leads to an immediate win, or if the recursive call for the opponent returns "false," the current player wins.
  • Memoization: Store the result of each bitmask state to prevent re-calculating the same game configuration.

Example explanation

maxChoosableInteger = 10, desiredTotal = 11.

  1. Player 1 can pick 10.
  2. Now the total is 10, and 1 is needed to win.
  3. Player 2's turn. Player 2 must pick an available number (1 through 9).
  4. Any number Player 2 picks will make the total >= 11.
  5. Player 2 wins. Wait, Player 1 plays optimally. Player 1 would realize that if they pick any number x < 11, Player 2 might win on the next turn. However, if P1 picks 10, P2 definitely wins. P1 will try other paths to see if there's any choice that forces a P2 loss.

Common mistakes candidates make

  • Ignoring the total sum constraint: If the sum of all available numbers is less than desiredTotal, no one can ever win. This is an important edge case.
  • Exponential recursion: Not using a bitmask and memoization, leading to a O(2^N) complexity that times out for N > 20.
  • Confusing player turns: Failing to correctly implement the logic that "I win if I can put my opponent in a losing position."

Interview preparation tip

Practice problems involving "Two-player games" and "Optimal Play." The pattern is almost always: canWin(state) = exists move such that !canWin(next_state). Bitmasking is the most efficient way to track "used" items in these scenarios.

Similar Questions