An attendance record is a string with one letter per day: A for absent, L for late, P for present. A record earns an award when it has at most one A in total and never three or more L in a row.
Given the number of days n, count how many different records of length n earn the award. The count grows fast, so return it modulo 1,000,000,007.
Example 1
Input: n = 3 Output: 19 Why: 27 records in all; 7 have two or more A, and "LLL" fails
2 more examples and the constraints
Example 2
Input: n = 1 Output: 3 Why: "A", "L" and "P" all pass
Example 3
Input: n = 4 Output: 43 Why: count by state, one day at a time
Constraints
- 1 ≤ n ≤ 100,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- DP table by day and stateO(n)
- Six rolling countersO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 100,000 | Verdict |
|---|---|---|---|
| DP table by day and state | O(n) | Clear; stores every day | |
| Six rolling counters | O(n) | Best; constant memory |
n = number of days. Both do the same additions; the table also stores 6n numbers.
Edge cases to test
- One day. n = 1 gives 3: every single letter passes.
- Large n. n = 100,000 needs the modulo on every step, and 64-bit sums in Java and C++.
- Two absences. No transition adds A to a record that already has one, so "AA" is never counted.
- Three late days. L is only added when the late run is under 2, so "LLL" is never counted.
Common mistakes
- Sending a record that gains an A to the wrong state: A also ends the late run, so it lands in state 3 (one absence, no late tail).
- Taking the modulo only at the end, after the numbers have already overflowed.
- Summing the six final counts in a 32-bit int, which overflows before the last modulo.
How to talk through it
- 1Clarify. Is one absence allowed? Does the modulo apply to the final count only, or may I apply it as I go?
- 2Name the brute force. Try all 3ⁿ strings and check each; hopeless past n = 20.
- 3Find the states. Only absences so far (0 or 1) and the late tail (0 to 2) matter: 6 states.
- 4Code the rolling row. Build each new row of six from the old one; say why each line is right.
- 5Test out loud. Check n = 1 gives 3 and n = 3 gives 19 by hand, then mention the large case.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?