#903
Valid Permutations for DI Sequence
HardStringDynamic ProgrammingPrefix SumDynamic ProgrammingCombinatorics
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 count valid permutations based on the number of increasing and decreasing sequences. By leveraging combinatorial properties, we can efficiently compute the result without generating all permutations.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a DP array where dp[i] represents the number of valid permutations for the first i characters of s.
- 2Step 2: Use combinatorial logic to fill the DP array based on the counts of 'I' and 'D' in the string.
- 3Step 3: Return dp[n] as the result.
solution.py12 lines
1def count_valid_permutations(s):
2 MOD = 10**9 + 7
3 n = len(s)
4 dp = [0] * (n + 1)
5 dp[0] = 1
6
7 for i in range(1, n + 1):
8 dp[i] = dp[i - 1] * (i + 1) % MOD
9 if s[i - 1] == 'D':
10 dp[i] = dp[i - 1] * i % MOD
11
12 return dp[n]ℹ
Complexity note: The time complexity is O(n) because we iterate through the string once to fill the DP array. The space complexity is O(n) due to the DP array.
- 1Dynamic programming can reduce the complexity of counting problems.
- 2Understanding combinatorial properties is crucial for optimization.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.