Student Attendance Record II solution explained
Student Attendance Record II asks how many attendance strings of length n, made of P (present), L (late) and A (absent), contain fewer than two A's and never three L's in a row, with the count taken modulo 1,000,000,007. Track six states, the number of absences so far (0 or 1) times the number of trailing lates (0, 1 or 2), and update them once per day. That is O(n) time and O(1) space, and a 6 by 6 matrix power brings it to O(log n).
By Evin JohnPublished 9 min read
The problem, in plain terms
A school marks each day with one letter: P for present, L for late, A for absent. A record earns an award if the student was absent on fewer than two days in total and was never late three days in a row. Given a number of days n, count how many of the possible records of exactly that length earn the award. The count grows fast, so return it modulo 1,000,000,007.
The first part of this problem pair only asks you to check one given string, which is a one-line test: count the A's and look for the substring LLL. Part II flips it into counting, and that is where dynamic programming comes in.
| Days n | All records (3^n) | Award-earning records |
|---|---|---|
| 3 | 27 | 19 (LLL and every string with two or more A's are out) |
| 4 | 81 | 43 |
| 5 | 243 | 94 |
| 6 | 729 | 200 |
| 10 | 59,049 | 3,536 |
Check the length 3 row by hand once: 27 strings, minus the 7 that contain at least two A's, minus LLL, leaves 19. Doing one small case manually in an interview is a fast way to make sure you read both rules correctly.
What the interviewer is looking for
This is a counting problem disguised as a string problem. The interviewer wants to see you notice that you never need the actual strings, only a small summary of each prefix, and that you can name that summary precisely. Strong candidates also handle the modulo without overflow and can mention the logarithmic follow-up without being prompted.
Brute force
from itertools import product
def count_brute(n):
good = 0
for chars in product("PLA", repeat=n):
record = "".join(chars)
if record.count("A") < 2 and "LLL" not in record:
good += 1
return goodThe six states
Pattern: dynamic programming over a finite state machine. Whether a prefix can still be extended, and how, depends on two things only: the number of A's so far (0 or 1, since 2 is already a failure) and the number of L's at the very end (0, 1 or 2, since 3 is a failure). That makes six states. Adding a letter moves a record between them as follows.
| Letter | Allowed when | New state |
|---|---|---|
| P | always | (a, 0): the late streak resets |
| L | l is 0 or 1 | (a, l + 1) |
| A | a is 0 | (1, 0): the A also breaks the late streak |
MOD = 10**9 + 7
def count_records(n):
# ways[a][l]: valid records so far with a absences in total
# and l lates at the very end
ways = [[1, 0, 0], [0, 0, 0]]
for _ in range(n):
new = [[0, 0, 0], [0, 0, 0]]
for a in range(2):
for l in range(3):
w = ways[a][l]
if w == 0:
continue
new[a][0] = (new[a][0] + w) % MOD # add P
if l < 2:
new[a][l + 1] = (new[a][l + 1] + w) % MOD # add L
if a == 0:
new[1][0] = (new[1][0] + w) % MOD # add A
ways = new
return sum(map(sum, ways)) % MODThe table starts with one empty record in state (0, 0). Each day builds a fresh table from the old one, so a record cannot take two letters in the same day. Taking the modulo after every addition keeps the numbers small in any language.
The same idea in JavaScript
With only six numbers, many people write them as named variables. Every new value is a sum of old ones, so assign them all at once from the old values. The largest intermediate sum is about six times the modulus, far below the largest integer a JavaScript number stores exactly, so no BigInt is needed here.
function countRecords(n) {
const MOD = 1000000007;
// a0l0 = no absence, no trailing late; a1l2 = one absence, two trailing lates
let a0l0 = 1, a0l1 = 0, a0l2 = 0, a1l0 = 0, a1l1 = 0, a1l2 = 0;
for (let day = 0; day < n; day++) {
const noA = (a0l0 + a0l1 + a0l2) % MOD;
const withA = (a1l0 + a1l1 + a1l2) % MOD;
[a0l0, a0l1, a0l2, a1l0, a1l1, a1l2] = [
noA, // P after any no-absence record
a0l0, // L extends a run of zero lates
a0l1, // L extends a run of one late
(withA + noA) % MOD, // P after a one-absence record, or the A itself
a1l0,
a1l1,
];
}
return (a0l0 + a0l1 + a0l2 + a1l0 + a1l1 + a1l2) % MOD;
}Follow-up: very large n with a matrix power
The daily update is linear: the new six counts are fixed sums of the old six. That means it can be written as a 6 by 6 matrix, and n days of updates are the matrix raised to the n-th power. Repeated squaring computes that power in O(log n) matrix products of constant size. In Python, the integers here never overflow, but the modulo after each product keeps them small and fast.
MOD = 10**9 + 7
def count_records_fast(n):
# state index = 3 * absences + trailing lates; step[i][j] = ways from j to i
step = [[0] * 6 for _ in range(6)]
for a in range(2):
for l in range(3):
src = 3 * a + l
step[3 * a][src] += 1 # P
if l < 2:
step[3 * a + l + 1][src] += 1 # L
if a == 0:
step[3][src] += 1 # A
def mul(x, y):
return [[sum(x[i][k] * y[k][j] for k in range(6)) % MOD
for j in range(6)] for i in range(6)]
power = [[int(i == j) for j in range(6)] for i in range(6)]
while n:
if n & 1:
power = mul(power, step)
step = mul(step, step)
n >>= 1
return sum(power[i][0] for i in range(6)) % MOD # start in state 0This is a strong follow-up answer even if you only describe it. For a scale sense, the loop needs one update per day, so n of 10^18 would never finish, while the matrix version handles it in about 60 squarings. Our matrix code prints 665873632 for that n; that single value was not checked by any second method.
Another way to see it: split around the absence
If you first count records with no A at all, call that f(k) for length k, then every record with exactly one A is a no-A record of length i, the A, and a no-A record of length n - 1 - i. The total is f(n) plus the sum of f(i) × f(n - 1 - i) over every position i. The no-A counts start at f(0), f(1), f(2) = 1, 2 and 4, and from length 3 on a valid string must end in P, PL or PLL, so f(k) = f(k - 1) + f(k - 2) + f(k - 3). This version is O(n²) as a plain sum, which makes it a nice check rather than the final answer.
Complexity summary
| Approach | Time | Extra space |
|---|---|---|
| Every string | O(3^n × n) | O(n) |
| Split around the A | O(n²) | O(n) |
| Six-state DP | O(n) | O(1) |
| Matrix power | O(log n) with 6 by 6 products | O(1) |
Edge cases to test
- n = 0: one empty record, which breaks no rule. Ask whether the interviewer wants that or treats n as at least 1.
- n = 3, where LLL is the only late failure and the hand count of 19 is easy to confirm.
- Large n, to confirm every addition is reduced and nothing overflows in fixed-width languages.
- A record like LLALL, which is valid: the A resets the late streak.
Common mistakes
- Treating the late rule as a total count of L's rather than a run of consecutive ones.
- Forgetting that an A resets the late streak just like a P does.
- Updating the counters in place so that a value is read after it was already overwritten for the new day.
- Applying the modulo only at the end, which overflows 32-bit and 64-bit integers long before the loop finishes.
- Allowing two A's because the rule says fewer than two, not at most two.
How to explain it out loud
Fictional example
- Candidate
- I don't need the strings themselves. To know what I can append next, I only need how many absences I've used, zero or one, and how many lates I'm ending on, zero, one or two.
- Candidate
- So that's six counters. P sends any state to the same absence count with zero lates, L bumps the late count if it's below two, and A is only allowed with zero absences and resets lates.
- Candidate
- That's linear time and constant space, with a modulo after each addition. If n were enormous, the update is a fixed linear map, so I could raise a six by six matrix to the n-th power in log n steps.
Related problems
Another counting DP that works modulo a large prime, with wildcard characters that multiply the number of choices, is Decode Ways II. For a DP where the state is a pair of substrings rather than a few counters, see Scramble String.
Practicing counting problems with Natively
Counting problems go wrong quietly, because a slightly wrong recurrence still prints a plausible number. In practice on your Mac or Windows machine, Natively can read the statement from a screenshot and write an approach and code to compare with yours, which is a quick way to catch a missed transition. Afterward, the session transcript shows whether you stated your states before coding. See how an AI helper fits LeetCode-style practice.
Questions people ask
How do you solve Student Attendance Record II?
Count records with dynamic programming over six states: absences so far (0 or 1) and lates at the end (0, 1 or 2). Each day, P resets the late count, L adds one if below two, and A is allowed only with no absences yet.
What is the time complexity of Student Attendance Record II?
The six-state DP is O(n) time and O(1) space. Writing the daily update as a 6 by 6 matrix and raising it to the n-th power by repeated squaring brings time down to O(log n).
Why is the answer taken modulo 1,000,000,007?
The number of valid records grows exponentially with n, so it quickly exceeds any fixed-width integer. Reducing after every addition keeps each value small and the final answer exact modulo that prime.
Does an absence reset the late streak?
Yes. The rule is about three lates in a row, so any other letter, P or A, ends the streak. Forgetting this undercounts the valid records.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
