
Sponsored
Sponsored
This approach leverages dynamic programming to count eligible attendance records. We define a function dp[i][a][l], which represents the number of valid sequences of length i with a absences and l consecutive lates. The transitions will account for adding 'P', 'A', or 'L' to existing records, ensuring we respect the problem's constraints.
Time complexity: O(n), Space complexity: O(1), as we use only a fixed amount of space irrespective of n.
1function checkRecord(n) {
2 const MOD = 1000000007;
3 let dp = Array.from({ length: 2 }, () =>
4 Array.from({ length: n + 1 }, () => Array(3).fill(0))
5 );
6 dp[0][0][0] = 1;
7 for (let i = 0; i < n; i++) {
8 for (let a = 0; a <= 1; a++) {
9 for (let l = 0; l < 3; l++) {
10 dp[a][i + 1][0] = (dp[a][i + 1][0] + dp[a][i][l]) % MOD;
11 if (a === 0) {
12 dp[1][i + 1][0] = (dp[1][i + 1][0] + dp[a][i][l]) % MOD;
13 }
14 if (l < 2) {
15 dp[a][i + 1][l + 1] = (dp[a][i + 1][l + 1] + dp[a][i][l]) % MOD;
16 }
17 }
18 }
19 }
20 let total = 0;
21 for (let a = 0; a <= 1; a++) {
22 for (let l = 0; l < 3; l++) {
23 total = (total + dp[a][n][l]) % MOD;
24 }
25 }
26 return total;
27}
28
29console.log(checkRecord(2));The JavaScript implementation follows the same dynamic programming strategy using nested arrays to track state-transition counts dynamically updated for each string length up to n.
This approach uses matrix exponentiation to efficiently solve the problem by leveraging the recursive relationship of the transformation matrices, which model the state transitions of the sequences. The matrix exponentiation technique drastically reduces the time complexity by harnessing fast exponentiation properties.
Time complexity: O(log n), Space complexity: O(1), because we only manipulate fixed-size arrays.
1
This Python code uses functions for matrix multiplication and exponentiation in order to model the problem's constraints and efficiently calculate the total valid sequences.