#3337

Total Characters in String After Transformations II

Hard
Hash TableMathStringDynamic ProgrammingCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + 26^3 log t)
Space
O(1)
O(26^2)
💡

Intuition

Time O(n + 26^3 log t)Space O(26^2)

Instead of transforming the string character by character for each transformation, we can model the transformations as a mathematical operation using matrix exponentiation. This allows us to compute the final transformation in logarithmic time with respect to t.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a transformation matrix where each row represents the effect of transforming a character based on the nums array.
  2. 2Step 2: Use matrix exponentiation to compute the transformation matrix raised to the power of t.
  3. 3Step 3: Multiply the original character counts by the resulting matrix to get the final counts after t transformations.
solution.py27 lines
1# Full working Python code
2
3def matrix_mult(A, B):
4    return [[sum(x * y for x, y in zip(A_row, B_col)) % (10**9 + 7) for B_col in zip(*B)] for A_row in A]
5
6def matrix_pow(mat, p):
7    res = [[1 if i == j else 0 for j in range(26)] for i in range(26)]
8    while p:
9        if p % 2:
10            res = matrix_mult(res, mat)
11        mat = matrix_mult(mat, mat)
12        p //= 2
13    return res
14
15def total_characters(s, t, nums):
16    MOD = 10**9 + 7
17    trans_matrix = [[0] * 26 for _ in range(26)]
18    for i in range(26):
19        trans_matrix[i][(i + nums[i]) % 26] += 1
20    final_matrix = matrix_pow(trans_matrix, t)
21    count = [0] * 26
22    for char in s:
23        count[ord(char) - ord('a')] += 1
24    result_length = 0
25    for i in range(26):
26        result_length = (result_length + final_matrix[i][i] * count[i]) % MOD
27    return result_length

Complexity note: The time complexity is O(n) for counting characters plus O(26^3 log t) for matrix exponentiation, where 26 is the number of letters in the alphabet. The space complexity is O(26^2) for storing the transformation matrix.

  • 1Matrix exponentiation can drastically reduce the time complexity for repeated transformations.
  • 2Understanding how to model problems mathematically can lead to more efficient solutions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.