Student Attendance Record II - Problem

An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:

  • 'A': Absent
  • 'L': Late
  • 'P': Present

Any student is eligible for an attendance award if they meet both of the following criteria:

  • The student was absent ('A') for strictly fewer than 2 days total
  • The student was never late ('L') for 3 or more consecutive days

Given an integer n, return the number of possible attendance records of length n that make a student eligible for an attendance award.

The answer may be very large, so return it modulo 109 + 7.

Input & Output

Example 1 — Small Case
$ Input: n = 2
Output: 8
💡 Note: Valid 2-character strings: PP, PL, PA, LP, LL, LA, AP, AL. Invalid: AA (2 absents), LLL would be invalid if n=3
Example 2 — Minimum Size
$ Input: n = 1
Output: 3
💡 Note: All single characters are valid: P, L, A (none violate the constraints)
Example 3 — Larger Input
$ Input: n = 10101
Output: 183236316
💡 Note: Large input demonstrating modular arithmetic is required due to exponential growth

Constraints

  • 1 ≤ n ≤ 105
  • Answer fits in 32-bit integer after modulo operation

Visualization

Tap to expand
INPUTALGORITHMRESULTn = 2Constraints:< 2 Absents (A)< 3 Consecutive Lates (L)Characters: A, L, PValid Examples:PP, PL, PALP, LL, LAAP, AL1DP State Setupdp[pos][absent][late]2State TransitionsP: reset late countA: increment absentL: increment late3Fill DP TableBottom-up approach4Valid Records Count8valid stringsof length 2All strings:PP, PL, PA, LPLL, LA, AP, ALAA (invalid)Result mod 10⁹+7Key Insight:Track attendance state (absent count + consecutive late days) to efficiently count all valid records using dynamic programming with O(n) time complexity.TutorialsPoint - Student Attendance Record II | Bottom-Up Dynamic Programming
Asked in
Google 15 Facebook 8 Amazon 12
28.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen