Problem Description
Given a number n, count the number of possible attendance records of length n that make a student eligible for an award. A record is a string where the character 'A' represents Absent, 'L' represents Late, and 'P' represents Present. A record is eligible if it contains strictly fewer than 2 'A's and does not contain 3 or more consecutive 'L's. The answer should be returned modulo 10^9+7.
Key Insights
- Use Dynamic Programming to simulate the sequence day by day.
- Represent the state using the number of days processed, the count of 'A's used (0 or 1), and the current count of consecutive 'L's (0, 1, or 2).
- For each day, consider adding a 'P', 'L', or 'A' while updating the state.
- Only allow an 'A' if none has been used yet; only allow 'L' if the current consecutive count is less than 2.
- Modular arithmetic is required at each step to prevent overflow.
Space and Time Complexity
Time Complexity: O(n) – We iterate through n days, and for each day we update a constant number of states. Space Complexity: O(n) if using a full DP table, but it can be optimized to O(1) since only the previous states are needed.
Solution
We solve the problem using a 3D dynamic programming approach where dp[i][a][l] represents the number of valid sequences of length i having used a number of 'A's and ending with l consecutive 'L's. The recurrence updates the dp table by considering three actions each day:
- Append 'P': Resets consecutive 'L' count to 0.
- Append 'L': Increments the consecutive 'L' count (ensuring it stays below 3).
- Append 'A': Increases the absence count (allowed only if no 'A' has been used yet) and resets consecutive 'L' count. After processing n days, the answer is the sum of all valid states modulo 10^9+7.
Code Solutions
Below are the implementations in Python, JavaScript, C++, and Java with line-by-line comments.