Leetcode #837: New 21 Game
In this guide, we solve Leetcode #837 New 21 Game in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Alice plays the following game, loosely based on the card game "21". Alice starts with 0 points and draws numbers while she has less than k points.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Math, Dynamic Programming, Sliding Window, Probability and Statistics
Intuition
We are looking for a contiguous region that satisfies a constraint, which is a classic sliding-window signal.
Expanding and shrinking the window lets us maintain validity without restarting the scan.
Approach
Grow the window with a right pointer, and shrink from the left only when the constraint is violated.
Track the best window as you go to keep the solution linear.
Steps:
- Expand the right end of the window.
- While invalid, move the left end to restore constraints.
- Update the best window found.
Example
Input: n = 10, k = 1, maxPts = 10
Output: 1.00000
Explanation: Alice gets a single card, then stops.
Python Solution
class Solution:
def new21Game(self, n: int, k: int, maxPts: int) -> float:
def dfs(i: int) -> float:
if i >= k:
return int(i <= n)
if i == k - 1:
return min(n - k + 1, maxPts) / maxPts
return dfs(i + 1) + (dfs(i + 1) - dfs(i + maxPts + 1)) / maxPts
return dfs(0)
Complexity
The time complexity is O(n). The space complexity is O(1) to O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.