- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 49 lines of Python from the credited upstream file 3337.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 3 def lengthAfterTransformations(self, s: str, t: int, nums: list[int]) -> int:4 MOD = 1_000_000_0075 6 def matrixMult(A: list[list[int]], B: list[list[int]]) -> list[list[int]]:7 """Returns A * B."""8 sz = len(A)9 C = [[0] * sz for _ in range(sz)]10 for i in range(sz):11 for j in range(sz):12 for k in range(sz):13 C[i][j] += A[i][k] * B[k][j]14 C[i][j] %= MOD15 return C16 17 def matrixPow(M: list[list[int]], n: int) -> list[list[int]]:18 """Returns M^n."""19 if n == 0:20 return [[1 if i == j else 0 21 for j in range(len(M))]22 for i in range(len(M))]23 if n % 2 == 1:24 return matrixMult(M, matrixPow(M, n - 1))25 return matrixPow(matrixMult(M, M), n 2)26 27 28 T = self._getTransformationMatrix(nums)29 poweredT = matrixPow(T, t)30 count = [0] * 2631 lengths = [0] * 2632 33 for c in s:34 count[ord(c) - ord('a')] += 135 36 for i in range(26):37 for j in range(26):38 lengths[j] += count[i] * poweredT[i][j]39 lengths[j] %= MOD40 41 return sum(lengths) % MOD42 43 def _getTransformationMatrix(self, nums: list[int]) -> list[list[int]]:44 T = [[0] * 26 for _ in range(26)]45 for i, steps in enumerate(nums):46 for step in range(1, steps + 1):47 T[i][(i + step) % 26] += 148 return T49