Total Characters in String After Transformations I - Problem

Imagine a magical string transformation system where each letter evolves through the alphabet! You are given a string s and an integer t representing the number of transformation rounds to perform.

In each transformation, every character follows these evolution rules:

  • If the character is 'z', it splits into the string "ab"
  • Otherwise, it advances to the next character in the alphabet ('a''b', 'b''c', etc.)

Your task is to determine the total length of the resulting string after exactly t transformations. Since the result can grow exponentially large, return the answer modulo 109 + 7.

Example: Starting with "az" and t=2:
Round 1: "az""bab" (a→b, z→ab)
Round 2: "bab""cbab" (b→c, a→b, b→c)
Final length: 4

Input & Output

example_1.py — Basic Transformation
$ Input: s = "abcxyz", t = 1
Output: 7
💡 Note: After 1 transformation: 'a'→'b', 'b'→'c', 'c'→'d', 'x'→'y', 'y'→'z', 'z'→'ab'. Result: "bcdyzab" with length 7.
example_2.py — Multiple Z's
$ Input: s = "aaz", t = 1
Output: 4
💡 Note: After 1 transformation: 'a'→'b', 'a'→'b', 'z'→'ab'. Result: "bbab" with length 4.
example_3.py — No Transformations
$ Input: s = "abc", t = 0
Output: 3
💡 Note: With t=0, no transformations are applied, so the length remains 3.

Visualization

Tap to expand
🧬 Alphabet Evolution LaboratoryaGeneration 0: 2 organismszGeneration 0: 1 organismEvolutionbGeneration 1: 2 organisms (from a)aGeneration 1: 1 organismbGeneration 1: 1 organism(both from z split)💡 Key InsightInstead of tracking each individual organism (character),we just count populations of each type!This reduces complexity from O(2^t) to O(26×t)
Understanding the Visualization
1
Population Census
Count how many of each letter type we have initially
2
Evolution Rules
Each generation: a→b, b→c, ..., y→z, z→ab (splits!)
3
Track Populations
Update counts without tracking individual organisms
Key Takeaway
🎯 Key Insight: Count character frequencies instead of building the actual string - this transforms an exponential problem into a linear one!

Time & Space Complexity

Time Complexity
⏱️
O(26 * t)

For each of t transformations, we update counts for 26 characters

n
2n
Linear Growth
Space Complexity
O(1)

Only need arrays of size 26 to store character counts

n
2n
Linear Space

Constraints

  • 1 ≤ s.length ≤ 105
  • 1 ≤ t ≤ 104
  • s consists only of lowercase English letters
  • Answer must be returned modulo 109 + 7
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
43.7K Views
Medium Frequency
~25 min Avg. Time
1.8K 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