Find the Original Typed String II Problem
Description
LeetCode Problem 3333.
Alice is attempting to type a specific string on her computer. However, she tends to be clumsy and may press a key for too long, resulting in a character being typed multiple times.
You are given a string word, which represents the final output displayed on Alice's screen. You are also given a positive integer k.
Return the total number of possible original strings that Alice might have intended to type, if she was trying to type a string of size at least k.
Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: word = "aabbccdd", k = 7
Output: 5
Explanation:
The possible strings are: "aabbccdd", "aabbccd", "aabbcdd", "aabccdd", and "abbccdd".
Example 2:
Input: word = "aabbccdd", k = 8
Output: 1
Explanation:
The only possible string is "aabbccdd".
Example 3:
Input: word = "aaabbb", k = 3
Output: 8
Constraints:
1 <= word.length <= 5 * 10^5wordconsists only of lowercase English letters.1 <= k <= 2000
Solution
Approach: Count everything, subtract the too-short strings
Split word into runs of equal letters. The original string keeps between 1 and len letters of each run, so ignoring the length rule there are a = the product of the run lengths candidates. The answer is a minus the number of candidates shorter than k.
Every candidate has at least one letter per run, so with m runs a candidate of length below k takes only x < k - m extra letters. If k <= m every candidate is long enough and the answer is a.
Otherwise let the run lengths minus one be nums, and let f[i][j] be the number of ways to take j extra letters from the first i runs. Run i with x = nums[i - 1] can give 0..x extra letters, so f[i][j] is the sum of f[i - 1][j - l] for l in 0..min(x, j). A prefix sum over f[i - 1] computes each row in O(k). The number of short candidates is the sum of f[m][j] for j < k (with k already reduced by m), and the answer is a minus that, modulo 10^9 + 7.
Complexity: O(n + k^2) time and O(k^2) space.
from itertools import accumulate
class Solution:
def possibleStringCount(self, word: str, k: int) -> int:
mod = 10**9 + 7
nums = []
ans = 1
cur = 0
for i, c in enumerate(word):
cur += 1
if i == len(word) - 1 or c != word[i + 1]:
if cur > 1:
if k > 0:
nums.append(cur - 1)
ans = ans * cur % mod
cur = 0
k -= 1
if k < 1:
return ans
m = len(nums)
f = [[0] * k for _ in range(m + 1)]
f[0][0] = 1
for i, x in enumerate(nums, 1):
s = list(accumulate(f[i - 1], initial=0))
for j in range(k):
f[i][j] = (s[j + 1] - s[j - min(x, j)] + mod) % mod
return (ans - sum(f[m][j] for j in range(k))) % mod