LeetCode 903, Hard. Topics: String, Dynamic Programming, Prefix Sum. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 20 parametrized pytest cases, and a playground notebook:
Problem
You are given a string s of length n where s[i] is either:
'D' means decreasing, or
'I' means increasing.
A permutation perm of n + 1 integers of all the integers in the range [0, n] is called a valid permutation if for all valid i:
- If
s[i] == 'D', then perm[i] > perm[i + 1], and
- If
s[i] == 'I', then perm[i] < perm[i + 1].
Return the number of valid permutations perm. Since the answer may be large, return it modulo 10^9 + 7.
Examples
Explanation: The 5 valid permutations of (0, 1, 2, 3) are:
(1, 0, 3, 2)
(2, 0, 3, 1)
(2, 1, 3, 0)
(3, 0, 2, 1)
(3, 1, 2, 0)
Constraints
n == s.length
1 <= n <= 200
s[i] is either 'I' or 'D'.
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
Last modified on September 7, 2026