
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.
1def checkRecord(n):
2 MOD = 10**9 + 7
3 dp = [[[0 for _ in range(3)] for _ in range(n + 1)] for _ in range(2)]
4 dp[0][0][0] = 1
5 for i in range(n):
6 for a in range(2):
7 for l in range(3):
8 dp[a][i + 1][0] = (dp[a][i + 1][0] + dp[a][i][l]) % MOD
9 if a == 0:
10 dp[1][i + 1][0] = (dp[1][i + 1][0] + dp[a][i][l]) % MOD
11 if l < 2:
12 dp[a][i + 1][l + 1] = (dp[a][i + 1][l + 1] + dp[a][i][l]) % MOD
13 return sum(dp[a][n][l] for a in range(2) for l in range(3)) % MOD
14
15n = 2
16print(checkRecord(n))The Python implementation similarly utilizes dynamic programming, leveraging lists to maintain counts of state transitions dynamically updated for each sequence 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
The JavaScript solution leverages arrays to conduct matrix operations, embracing matrix exponentiation to efficiently compute the number of valid attendance records.