Divisor Game
LeetCode 1025 · ಸುಲಭ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Win ⇔ n is even.
ನಾನು Divisor Game (LeetCode 1025) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Game DP ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಸುಲಭ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
A number is a winning position if some legal move leaves the opponent on a losing position. Building that table from 1 upward reveals a pattern: even numbers win and odd numbers lose. Whoever holds an even number can always subtract 1 and hand over an odd one; from an odd number every divisor is odd, so the opponent always gets an even number back.
Approach
- 1
dp[i] = True if the player to move at i can force a win.
- 2
Try every divisor x < i; if dp[i − x] is False, i is a win.
- 3
dp[n] answers the question — and the table shows it equals n % 2 == 0.
- 4
Final version returns the parity directly.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ · ಮೊದಲ ಆಲೋಚನೆಯಿಂದ ಅಂತಿಮ ಪರಿಹಾರದವರೆಗೆ
dp over positions and divisors.
Even wins.
Win / lose tablePythonO(n²) time · O(n) space
class Solution:
def divisorGame(self, n: int) -> bool:
#2
#Alice - 1 2%1 = 0 remaining 1
#Bom - 1 - bob can't take any move
#3 divisor - 1,2,3
#Alice -1
#bob got -2 winning position
#4 divisor - 1,2,3
#alice took 1 remaining 3
#bob gets 3 - loosing position
dp= [False]*(n+1)
for i in range(1,n+1):
for x in range(1,i):
if i%x==0 and dp[i-x]==False: #(4-1) is a move for loosing position
dp[i]=True #then current posistion 4 is an winning position
return dp[n]ParityPythonO(1)
class Solution:
def divisorGame(self, n: int) -> bool:
return n%2==0Divisor Game — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Divisor Game ಹಿಂದಿನ intuition ಏನು?
A number is a winning position if some legal move leaves the opponent on a losing position. Building that table from 1 upward reveals a pattern: even numbers win and odd numbers lose. Whoever holds an even number can always subtract 1 and hand over an odd one; from an odd number every divisor is odd, so the opponent always gets an even number back.
Divisor Game (LeetCode 1025) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. dp[i] = True if the player to move at i can force a win. 2. Try every divisor x < i; if dp[i − x] is False, i is a win. 3. dp[n] answers the question — and the table shows it equals n % 2 == 0. 4. Final version returns the parity directly.
Divisor Game ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(1) final (O(n²) for the table). Space: O(1). (Accepted approach: Parity.)
Divisor Game ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
n = 1 is a loss: no x with 0 < x < 1 exists.
Divisor Game ಅನ್ನು ಪರಿಹರಿಸಲು ಒಂದಕ್ಕಿಂತ ಹೆಚ್ಚು ಮಾರ್ಗಗಳಿವೆಯೇ?
Win / lose table (O(n²) time · O(n) space): dp over positions and divisors. Parity (O(1)): Even wins.