Student Attendance Record II - Problem

A school wants to determine how many different valid attendance records of length n are possible for awarding perfect attendance certificates.

Each day in an attendance record is marked with one of three characters:

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

To qualify for an attendance award, a student must meet both criteria:

  1. Be absent ('A') for strictly fewer than 2 days total (0 or 1 absence)
  2. Never be 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 the award. Since the answer can be very large, return it modulo 109 + 7.

Example: For n = 2, valid records include "PP", "AP", "PA", "LP", "PL", "AL", "LA", "LL" (8 total).

Input & Output

example_1.py โ€” Basic Case
$ Input: n = 2
โ€บ Output: 8
๐Ÿ’ก Note: Valid 2-day records: "PP", "AP", "PA", "LP", "PL", "AL", "LA", "LL". All have โ‰ค1 absence and no 3+ consecutive lates.
example_2.py โ€” Single Day
$ Input: n = 1
โ€บ Output: 3
๐Ÿ’ก Note: Valid 1-day records: "P", "A", "L". All single characters automatically satisfy both criteria.
example_3.py โ€” Edge Case
$ Input: n = 10101
โ€บ Output: 183236316
๐Ÿ’ก Note: For large n, the answer involves complex DP calculations and must be returned modulo 10^9 + 7.

Constraints

  • 1 โ‰ค n โ‰ค 105
  • Answer fits in 32-bit integer after taking modulo
  • Must handle large n efficiently

Visualization

Tap to expand
Attendance State Machine(0,0,0)StartCount: 1(i,0,0)No A, No L(i,0,1)No A, 1L(i,1,0)1A, No LValidFinal States+P+L+AKey Insight: Instead of generating 3^n sequences,we count transitions between valid states in O(n) time!DP Recurrence: dp[i+1][j'][k'] += dp[i][j][k] for valid transitions
Understanding the Visualization
1
State Definition
Each state tracks: current day, total absences (0 or 1), consecutive lates (0, 1, or 2)
2
Valid Transitions
From each state, we can add P (always), A (if no prior absence), or L (if <2 consecutive)
3
Count Accumulation
Instead of generating sequences, we count how many ways to reach each valid state
4
Final Answer
Sum all ways to reach any valid final state after n days
Key Takeaway
๐ŸŽฏ Key Insight: Transform the problem from sequence generation to state counting using DP, reducing complexity from O(3^n) to O(n)
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
41.2K Views
Medium Frequency
~35 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