#2466
Count Ways To Build Good Strings
MediumDynamic ProgrammingDynamic ProgrammingRecursionMemoization
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses dynamic programming to efficiently count the number of good strings by storing previously computed results. This avoids redundant calculations and allows us to build up the count iteratively.
⚙️
Algorithm
4 steps- 1Step 1: Create a dp array where dp[i] represents the number of good strings of length i.
- 2Step 2: Initialize dp[0] = 1 (the empty string).
- 3Step 3: For each length from 1 to high, calculate dp[i] as the sum of dp[i - zero] and dp[i - one] if those indices are valid.
- 4Step 4: Sum the values in dp from index low to high to get the final count, and return it modulo 10^9 + 7.
solution.py10 lines
1def countGoodStrings(low, high, zero, one):
2 MOD = 10**9 + 7
3 dp = [0] * (high + 1)
4 dp[0] = 1
5 for i in range(1, high + 1):
6 if i - zero >= 0:
7 dp[i] = (dp[i] + dp[i - zero]) % MOD
8 if i - one >= 0:
9 dp[i] = (dp[i] + dp[i - one]) % MOD
10 return sum(dp[low:high + 1]) % MODℹ
Complexity note: The time complexity is O(n) because we iterate through lengths from 1 to high once, and the space complexity is O(n) due to the dp array storing counts for each length.
- 1Dynamic programming can significantly reduce the number of calculations by storing intermediate results.
- 2Understanding the problem constraints helps in formulating the right approach.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.