- 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
- 60 lines of Java from the credited upstream file 3337.java.
- The implementation visibly relies on sequence storage.
- 9 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 public int lengthAfterTransformations(String s, int t, List<Integer> nums) {4 5 int[][] T = getTransformationMatrix(nums);6 int[][] poweredT = matrixPow(T, t);7 int[] count = new int[26];8 9 long[] lengths = new long[26];10 11 for (final char c : s.toCharArray())12 ++count[c - 'a'];13 14 for (int i = 0; i < 26; ++i)15 for (int j = 0; j < 26; ++j) {16 lengths[j] += (long) count[i] * poweredT[i][j];17 lengths[j] %= MOD;18 }19 20 return (int) (Arrays.stream(lengths).sum() % MOD);21 }22 23 private static final int MOD = 1_000_000_007;24 25 private int[][] getTransformationMatrix(List<Integer> nums) {26 int[][] T = new int[26][26];27 for (int i = 0; i < nums.size(); ++i)28 for (int step = 1; step <= nums.get(i); ++step)29 ++T[i][(i + step) % 26];30 return T;31 }32 33 private int[][] getIdentityMatrix(int sz) {34 int[][] I = new int[sz][sz];35 for (int i = 0; i < sz; ++i)36 I[i][i] = 1;37 return I;38 }39 40 41 private int[][] matrixMult(int[][] A, int[][] B) {42 final int sz = A.length;43 int[][] C = new int[sz][sz];44 for (int i = 0; i < sz; ++i)45 for (int j = 0; j < sz; ++j)46 for (int k = 0; k < sz; ++k)47 C[i][j] = (int) ((C[i][j] + (long) A[i][k] * B[k][j]) % MOD);48 return C;49 }50 51 52 private int[][] matrixPow(int[][] M, int n) {53 if (n == 0)54 return getIdentityMatrix(M.length);55 if (n % 2 == 1)56 return matrixMult(M, matrixPow(M, n - 1));57 return matrixPow(matrixMult(M, M), n / 2);58 }59}60