DDSA Solutions

3335. Total Characters in String After Transformations I

Time: O(26 * t)
Space: O(26)

Problem Overview

Total Characters in String After Transformations I (Medium) asks you to solve a structured algorithmic task. This is a common Hash Table / Math pattern in coding interviews. Track char frequencies; each step 'z' splits to 'a'+'b'; use array rotation.

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Approach

Track char frequencies; each step 'z' splits to 'a'+'b'; use array rotation.

Related patterns: Hash Table, Math, String

3335.cs
C#
// Approach: Track char frequencies; each step 'z' splits to 'a'+'b'; use array rotation.
// Time: O(26 * t) Space: O(26)

public class Solution
{
    public int LengthAfterTransformations(string s, int t)
    {
        const int MOD = 1_000_000_007;
        int[] count = new int[26];

        foreach (char c in s)
            count[c - 'a']++;

        while (t-- > 0)
        {
            int[] newCount = new int[26];
            // 'a' -> 'b', 'b' -> 'c', ..., 'y' -> 'z'
            for (int i = 0; i < 25; i++)
                newCount[i + 1] = count[i];
            // 'z' -> 'ab'
            newCount[0] = count[25];
            newCount[1] = (newCount[1] + count[25]) % MOD;
            count = newCount;
        }

        return count.Aggregate(0, (a, b) => (a + b) % MOD);
    }
}
Was this solution helpful?

Related Problems