Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
Given a positive integer n, return true if and only if Alice wins the game otherwise return false, assuming both players play optimally.
Example 1:
Input: n = 1 Output: true Explanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.
Example 2:
Input: n = 2 Output: false Explanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).
Example 3:
Input: n = 4 Output: true Explanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).
Constraints:
1 <= n <= 105This approach uses Dynamic Programming to determine if Alice can win given n stones. We can maintain a boolean array dp where dp[i] represents whether Alice can win with i stones. A state is winning if there's any move that leaves the opponent in a losing state.
The array dp is initialized with false values. We iterate through each number up to n, checking all possible square numbers we can subtract. If there exists a square number such that the remaining stones leave Bob in a losing position, Alice is in a winning position.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n*sqrt(n)), Space Complexity: O(n)
This approach involves a recursive solution with memoization to cache previously computed results. If n is already solved, we return the cached result. Otherwise, we recursively check if any move leaves the opponent in a losing position.
We use a helper function to recursively determine if a current state is winning while memoizing results for efficiency. The memo array is initialized with -1. For each recursive call, the function checks if removing any square results in a losing state for the opponent.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n*sqrt(n)), Space Complexity: O(n)
| Approach | Complexity |
|---|---|
| Dynamic Programming Approach | Time Complexity: O(n*sqrt(n)), Space Complexity: O(n) |
| Recursive with Memoization | Time Complexity: O(n*sqrt(n)), Space Complexity: O(n) |
Stone Game - Leetcode 877 - Python • NeetCode • 34,440 views views
Watch 9 more video solutions →Practice Stone Game IV with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor