#2930
Number of Strings Which Can Be Rearranged to Contain Substring
MediumMathDynamic ProgrammingCombinatoricsCombinatorial CountingDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach calculates the number of good strings directly using combinatorial counting. We focus on ensuring the string contains the required characters and then distribute the remaining characters freely.
⚙️
Algorithm
3 steps- 1Step 1: Ensure the string contains at least one 'l', one 't', and two 'e's.
- 2Step 2: Calculate the number of remaining characters after placing 'leet'.
- 3Step 3: Use combinatorial formulas to calculate the arrangements of the remaining characters.
solution.py11 lines
1# Full working Python code
2MOD = 10**9 + 7
3
4def count_good_strings(n):
5 if n < 4:
6 return 0
7 # Calculate combinations
8 total = pow(26, n - 4, MOD)
9 arrangements = (n - 3) * (n - 2) * (n - 1) // 6
10 return (total * arrangements) % MOD
11ℹ
Complexity note: The time complexity is O(n) due to the power calculation, which is efficient compared to generating all strings.
- 1A good string must contain at least one 'l', one 't', and two 'e's.
- 2Combinatorial counting allows us to efficiently calculate arrangements instead of generating all strings.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.