Student Attendance Record II

HardDynamic Programming1d dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

An attendance record is a string over three letters: 'A' (absent), 'L' (late) and 'P' (present). A record earns an award when it has **fewer than 2** 'A' in total **and** never has **3 or more** 'L' in a row. Given n, count how many of the 3^n records of length n earn an award. The count can be huge, so return it modulo 10^9 + 7. A linear-time DP is enough. Matrix exponentiation gets it down to O(log n).

Examples

Input: n = 2
Output: 8
Of the 9 records of length 2, only "AA" has two absences, so 8 qualify.
Input: n = 1
Output: 3
"A", "L" and "P" all qualify.

Constraints

  • 1 <= n <= 10^5

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More 1d dp problems