Total Characters in String After Transformations I Problem
Description
LeetCode Problem 3335.
You are given a string s and an integer t, representing the number of transformations to perform. In one transformation, every character in s is replaced according to the following rules:
- If the character is
'z', replace it with the string"ab". - Otherwise, replace it with the next character in the alphabet. For example,
'a'is replaced with'b','b'is replaced with'c', and so on.
Return the length of the resulting string after exactly t transformations.
Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: s = "abcyy", t = 2
Output: 7
Explanation:
- First Transformation (t = 1):
- 'a' becomes 'b'
- 'b' becomes 'c'
- 'c' becomes 'd'
- 'y' becomes 'z'
- 'y' becomes 'z'
- String after the first transformation: "bcdzz"
- Second Transformation (t = 2):
- 'b' becomes 'c'
- 'c' becomes 'd'
- 'd' becomes 'e'
- 'z' becomes "ab"
- 'z' becomes "ab"
- String after the second transformation: "cdeabab"
- Final Length of the string: The string is "cdeabab", which has 7 characters.
Example 2:
Input: s = "azbk", t = 1
Output: 5
Explanation:
- First Transformation (t = 1):
- 'a' becomes 'b'
- 'z' becomes "ab"
- 'b' becomes 'c'
- 'k' becomes 'l'
- String after the first transformation: "babcl"
- Final Length of the string: The string is "babcl", which has 5 characters.
Constraints:
1 <= s.length <= 10^5sconsists only of lowercase English letters.1 <= t <= 10^5
Solution
Approach: Count letters per round
Only how many times each letter occurs matters, so keep an array of 26 counts. In one transformation every letter moves to the next one, except that z becomes ab: a receives the old count of z, b receives the old counts of a and z, and every other letter c receives the old count of the letter before it.
Apply this t times (taking everything modulo 10^9 + 7) and sum the 26 counts.
Complexity: O(26 * t) time and O(26 * t) space (O(26) if only two rows are kept).
class Solution:
def lengthAfterTransformations(self, s: str, t: int) -> int:
f = [[0] * 26 for _ in range(t + 1)]
for c in s:
f[0][ord(c) - ord("a")] += 1
for i in range(1, t + 1):
f[i][0] = f[i - 1][25]
f[i][1] = f[i - 1][0] + f[i - 1][25]
for j in range(2, 26):
f[i][j] = f[i - 1][j - 1]
mod = 10**9 + 7
return sum(f[t]) % mod