Python 0552.py
class Solution:
def checkRecord(self, n: int) -> int:
modulo = 1_000_000_007
# 6 states:
# 0 - never absent, never late
# 1 - never absent, late on previous day
# 2 - never absent, late on two last days
# 3 - absent once, never late
# 4 - absent once, late on previous day
# 5 - absent once, late on two last days
good = [ 1, 0, 0, 0, 0, 0 ]
for i in range(n):
good = [ sum(good[ : 3]), good[0], good[1], sum(good), good[3], good[4] ]
# a little bit faster if delaying modulo
if (i & 31) == 31: # temporary numbers still fit in 64 bit
for j in range(6):
good[j] %= modulo
return sum(good) % modulo
Difficulty
and has an acceptance rate of about 57% (200k+ submissions).
Typical patterns to solve this problem:
- Dynamic Programming
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The function computes the number of reward-eligible attendance records of length n under the constraints “no more than one ‘A’ (absent) and no three consecutive ‘L’ (late)”. It employs a compact dynamic programming (DP) approach with six aggregate states that capture the essential history needed to enforce the constraints. The DP iterates n times, updating the state vector and applying a modulus only periodically to keep intermediate values within 64-bit range. The final answer is the sum of all six states reduced modulo 1 000 000 007.
Key Steps
The DP state vector good holds counts for six mutually exclusive scenarios:
good = [1, 0, 0, 0, 0, 0] # initial: empty record, no A, no L
Each iteration corresponds to appending one character to every existing partial record. The transition is expressed by rebuilding good from the previous values:
good = [
sum(good[:3]), # add 'P' to any state without an A
good[0], # add 'L' to state 0 (now one trailing L)
good[1], # add 'L' to state 1 (now two trailing L)
sum(good), # add 'A' to any state (creates the single-A branch)
good[3], # add 'L' to state 3 (now one trailing L after an A)
good[4] # add 'L' to state 4 (now two trailing L after an A)
]
The first three entries keep the “no-A” branch alive, while the last three maintain the branch where exactly one ‘A’ has already appeared. The sums sum(good[:3]) and sum(good) aggregate the ways to extend records with a ‘P’ or an ‘A’, respectively.
After updating the vector, the code occasionally reduces each entry modulo modulo:
if (i & 31) == 31: # every 32 iterations
for j in range(6):
good[j] %= modulo
When the loop finishes, the answer is the total of all six states reduced modulo the prime:
return sum(good) % modulo
Edge Cases
When n is zero, the loop body never executes. The initial vector represents the empty record, and the final sum yields 1, correctly counting the single empty record as valid.
For very large n, intermediate counts can grow rapidly. The conditional modulo operation ensures that values stay within the 64-bit integer range for 32 consecutive iterations, preventing overflow while still avoiding the cost of a modulo on every step.
The state design inherently prevents illegal sequences: the “two trailing L” states never receive another ‘L’, and the “already-A” states never accept a second ‘A’. Consequently, any record that would violate the constraints is never counted.
Performance Optimizations
The algorithm compresses the full DP table into six aggregate counters, eliminating the need for a two-dimensional array indexed by position and history. This reduction cuts memory usage dramatically and makes each iteration a constant-time operation.
Using slice sums (sum(good[:3]) and sum(good)) leverages Python’s built-in fast C loops instead of manual accumulation.
Deferring the modulo operation to every 32nd iteration reduces the frequency of an expensive division while still guaranteeing that intermediate values remain safely bounded. The bitwise test (i & 31) == 31 is a cheap way to detect the 32-step boundary.
Overall, the implementation achieves a tight inner loop with minimal overhead, suitable for handling the maximum input size within the required time limits.
ELI5 - Simplified Explanation
Imagine keeping track of attendance in a classroom over many days. Each day, a student can either be present, late, or absent. There are special rules to follow, like not being allowed to be absent twice in total or having to avoid being late three times in a row.
This code acts like a tiny robot that counts how many different ways a student can attend school for a certain number of days without breaking those rules. The list filled with numbers keeps track of the current status of the student.
When the robot moves to the next day, it updates the list by looking at what happened before. For example, if the student was not late yesterday, they might be late today. If they were already late, they might become even later. Some paths are blocked because they would break the rules, so the robot ignores those.
The number at the beginning is a very large limit to make sure the math does not get too big to handle. Every so often, the robot shrinks the numbers to keep them tidy according to that limit. After all the days pass, the robot adds up all the safe ways the student could have attended school.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | Python | Go | |||||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| gouthampradhan | Java | ||||||||
| JoshCrozier | JS | ||||||||
| linouk23 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| MacJim | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| gouthampradhan | Java | ||||||||
| JoshCrozier | JavaScript | ||||||||
| linouk23 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| MacJim | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 551: Student Attendance Record I
Solved On The Same Day
- problem 2718: Sum of Matrix After Queries
- problem 2709: Greatest Common Divisor Traversal
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality