Problem 552

Abstract / Summary

Count the number of possible attendance records of length n that do not have more than one A and no more than two consecutive Ls.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
21 lines | 786 bytes | submitted June 24, 2024 | GitHub   90% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 57% (200k+ submissions).

Typical patterns to solve this problem:
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.89 | σ = 0.63

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
32 links | 20 authors | 8 languages

Videos

15 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

1 medium 1 hard
3 solutions   June 24, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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