Ctrl K

Square Pebble Duel

Hard
A pile holds pebbles pebbles. Two players take turns. On a turn, a player removes a number of pebbles that is a positive perfect square: 1, 4, 9, 16 and so on (never more than what is left). A player who cannot move loses. Both play optimally. Return True if the player who moves first wins, and False otherwise.
Example 1
pebbles=7 → False

You can take 1 or 4 pebbles, leaving 6 or 3. From 6 the opponent takes 1 and leaves 5; from 3 they take 1 and leave 2. Both are losing spots for the player to move, so the first player loses.

Example 2
pebbles=6 → True

Take 1 pebble: from 5 the opponent can only leave 4 or 1, and you take the rest.

Example 3
pebbles=9 → True

9 is a perfect square, so the first player takes every pebble at once.

Constraints
  • 1 ≤ pebbles ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsThief and Guard HardGrab Up to Three Cards HardKeep the Lighter Half HardMouse, Cat and Cheese HardMerge the Front Tiles Hard
loading Python…
Input
pebbles=7
Expected
False

Run checks the first 3 tests in your browser. Submit checks all 27 tests on the server, hidden ones included.