#3333
Find the Original Typed String II
HardStringDynamic ProgrammingPrefix SumDynamic ProgrammingCombinatorial Counting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * m) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n * m)Space O(n)
The optimal approach uses dynamic programming to count the number of valid original strings without generating them explicitly. We focus on counting combinations of characters that can be formed while ensuring the length constraint is satisfied.
⚙️
Algorithm
3 steps- 1Step 1: Count the frequency of each character in the input string.
- 2Step 2: Use dynamic programming to calculate the number of ways to form strings of lengths from 0 to the total length of the string.
- 3Step 3: Subtract the count of strings of length less than k from the total count to get the valid original strings.
solution.py13 lines
1def count_original_strings(word, k):
2 from collections import Counter
3 MOD = 10**9 + 7
4 freq = Counter(word)
5 total_length = sum(freq.values())
6 dp = [0] * (total_length + 1)
7 dp[0] = 1
8 for count in freq.values():
9 for i in range(total_length, 0, -1):
10 for j in range(1, count + 1):
11 if i - j >= 0:
12 dp[i] = (dp[i] + dp[i - j]) % MOD
13 return sum(dp[k:]) % MODℹ
Complexity note: The complexity is O(n * m) where n is the length of the string and m is the number of unique characters, as we iterate through the counts of each character to build the dynamic programming table.
- 1Understanding how to count combinations is crucial for solving problems involving repeated characters.
- 2Dynamic programming can significantly reduce the complexity of counting problems by avoiding explicit generation of all combinations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.