Total Characters in String After Transformations I - Problem

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 109 + 7.

Input & Output

Example 1 — Basic Transformation
$ Input: s = "ab", t = 1
Output: 2
💡 Note: After 1 transformation: 'a' becomes 'b', 'b' becomes 'c', so "ab" becomes "bc". Length is 2.
Example 2 — With 'z' Character
$ Input: s = "z", t = 1
Output: 2
💡 Note: After 1 transformation: 'z' becomes "ab", so "z" becomes "ab". Length changes from 1 to 2.
Example 3 — Multiple Transformations
$ Input: s = "a", t = 2
Output: 1
💡 Note: t=1: 'a'→'b', string becomes "b". t=2: 'b'→'c', string becomes "c". Final length is 1.

Constraints

  • 1 ≤ s.length ≤ 105
  • 1 ≤ t ≤ 109
  • s consists only of lowercase English letters

Visualization

Tap to expand
String Transformation Length INPUT Original String s: 'a' 'b' idx 0 idx 1 Transformation Rules: 'a'-'y' --> next char 'z' --> "ab" (z splits into 2 chars) Input Values: s = "ab" t = 1 (transforms) ALGORITHM STEPS 1 Count Characters Track count of each a-z a:1 b:1 c-z:0 2 Apply Transform Shift all counts forward 'a' --> 'b' 'b' --> 'c' 3 New Counts After t=1 transform a:0 b:1 c:1 4 Sum All Counts Result mod 10^9+7 "ab" --> "bc" (len=2) Wait... we need to verify FINAL RESULT After 1 transformation: Original: 'a' 'b' Transformed: 'b' 'c' len=2 Note: Example says output=4 This needs t=2 transforms OUTPUT 4 Key Insight: Use frequency counting instead of actual string manipulation. Track how many of each character exist after each transformation. When 'z' transforms, add its count to both 'a' and 'b'. Time: O(26 * t), Space: O(26). Apply modulo 10^9+7 to prevent overflow. TutorialsPoint - Total Characters in String After Transformations I | Optimal Solution
Asked in
Google 12 Meta 8 Amazon 6
8.9K Views
Medium Frequency
~35 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen