Valid Permutations For DI Sequence Problem
Description
LeetCode Problem 903.
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.
Example 1:
Input: s = "DID"
Output: 5
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)
Example 2:
Input: s = "D"
Output: 1
Constraints:
- n == s.length
- 1 <= n <= 200
- s[i] is either 'I' or 'D'.
Solution
Approach: DP on the Rank of the Last Value, with Prefix Sums
Trying all (n + 1)! permutations is hopeless for n = 200. The key observation is that only the relative order of the values matters, not the values themselves.
Build the permutation left to right. After placing i + 1 values, replace them by their ranks 0..i (the smallest gets 0). Let ways[j] be the number of valid arrangements of the first i + 1 positions whose last value has rank j.
Now add one more value and give it rank j among the i + 2 values. The earlier values with rank j or more shift up by one, the rest keep their rank. So the previous last value, with old rank k, ends up below the new one exactly when k < j:
- If
s[i] == 'I', the step goes up, sonextWays[j] = ways[0] + … + ways[j - 1]. - If
s[i] == 'D', the step goes down, sonextWays[j] = ways[j] + … + ways[i].
Each choice of old arrangement and new rank gives exactly one new arrangement, so nothing is counted twice. Computing each sum from scratch costs O(n) per entry and O(n3) in total. Instead keep a running sum: go up through j for 'I' and down for 'D', adding one ways entry per step.
Start with ways = [1] (one value, rank 0). The answer is the sum of ways after all of s, modulo 109 + 7.
For s = "DID": [1] → [1, 0] → [0, 1, 1] → [2, 2, 1, 0], and 2 + 2 + 1 + 0 = 5.
Complexity: O(n2) time and O(n) space, where n is the length of s.
class Solution:
def numPermsDISequence(self, s: str) -> int:
MOD = 10**9 + 7
# ways[j]: arrangements of the first i + 1 values that fit s[:i]
# and end with the j-th smallest of them (j = 0..i).
ways = [1]
for i in range(1, len(s) + 1):
next_ways = [0] * (i + 1)
if s[i - 1] == "I":
# The new last value has rank j, so the previous one had rank below j.
running = 0
for j in range(i + 1):
next_ways[j] = running
if j < i:
running = (running + ways[j]) % MOD
else:
# Going down: the previous last value had rank j or more (it shifts up past the new one).
running = 0
for j in range(i - 1, -1, -1):
running = (running + ways[j]) % MOD
next_ways[j] = running
ways = next_ways
return sum(ways) % MOD
Now write it from memory
Close the write-up and solve it yourself against the tests.