Find the Original Typed String II - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: word = "aabbcc", k = 4
Output: 7
💡 Note: Groups are [2,2,2]. We can shorten each group to length 1 or 2. Valid combinations with length ≥ 4: (1,1,2), (1,2,1), (1,2,2), (2,1,1), (2,1,2), (2,2,1), (2,2,2) = 7 ways
Example 2 — Minimum Length
$ Input: word = "aa", k = 1
Output: 2
💡 Note: Group is [2]. We can shorten to length 1 or 2. Both meet k=1 requirement, so 2 ways total
Example 3 — High Requirement
$ Input: word = "aab", k = 5
Output: 0
💡 Note: Groups are [2,1]. Maximum possible length is 2+1=3, which is less than k=5, so 0 ways

Constraints

  • 1 ≤ word.length ≤ 2000
  • word consists of lowercase English letters
  • 1 ≤ k ≤ 2000

Visualization

Tap to expand
Find the Original Typed String II INPUT word = "aabbcc" a a b b c c 3 consecutive groups: Group 1: "aa" (len=2) Group 2: "bb" (len=2) Group 3: "cc" (len=2) k = 4 (min length required) mod = 10^9 + 7 n = 6, groups = 3 lengths = [2, 2, 2] ALGORITHM STEPS 1 Count Total Combinations Multiply group lengths: 2 x 2 x 2 = 8 total 2 Use Prefix Sum + DP Count strings with len < k dp[i] = ways to get len i 3 Calculate Invalid Count Strings with length < 4: len 3: "abc" = 1 way 4 Subtract Invalid Result = total - invalid 8 - 1 = 7 Valid Strings (len >= 4): aabbcc aabc abcc abbc aabcc abbc aabc 7 valid combinations FINAL RESULT Counting Summary: Total Combinations 2 x 2 x 2 = 8 Invalid (len < 4) 1 string (abc) - Answer: 7 Output: 7 OK - Verified! Time: O(n), Space: O(n) Key Insight: Each group of consecutive identical characters can contribute 1 to len(group) chars to original string. Use DP with prefix sums to efficiently count strings with length < k, then subtract from total. Formula: answer = (product of all group lengths) - (count of strings with length < k) mod (10^9 + 7) TutorialsPoint - Find the Original Typed String II | Optimal Solution (DP with Prefix Sum)
Asked in
Google 15 Microsoft 12 Amazon 8
12.5K 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