LeetCode 0903. Valid Permutations for DI Sequence Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0903. Valid Permutations for DI Sequence

Description

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 109 + 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'.

Solutions

Solution 1: Dynamic Programming

We define f[i][j] as the number of permutations that satisfy the problem's requirements with the first i characters of the string ending with the number j. Initially, f[0][0]=1, and the rest f[0][j]=0. The answer is ∑_{j=0}n f[n][j].

Consider f[i][j], where j ∈ [0, i].

If the ith character s[i-1] is 'D', then f[i][j] can be transferred from f[i-1][k], where k ∈ [j+1, i]. Since k-1 can only be up to i-1, we move k one place to the left, so k ∈ [j, i-1]. Therefore, we have f[i][j] = ∑_{k=j}i-1 f[i-1][k].

If the ith character s[i-1] is 'I', then f[i][j] can be transferred from f[i-1][k], where k ∈ [0, j-1]. Therefore, we have f[i][j] = ∑_{k=0}j-1 f[i-1][k].

The final answer is ∑_{j=0}n f[n][j].

The time complexity is O(n3), and the space complexity is O(n2). Here, n is the length of the string.

We can optimize the time complexity to O(n2) using prefix sums.

Additionally, we can optimize the space complexity to O(n) using a rolling array.

PythonJavaC++GoTypeScriptPythonJavaC++GoTypeScriptPythonJavaC++GoTypeScript
class Solution: def numPermsDISequence(self, s: str) -> int: mod = 10**9 + 7 n = len(s) f = [[0] * (n + 1) for _ in range(n + 1)] f[0][0] = 1 for i, c in enumerate(s, 1): if c == "D": for j in range(i + 1): for k in range(j, i): f[i][j] = (f[i][j] + f[i - 1][k]) % mod else: for j in range(i + 1): for k in range(j): f[i][j] = (f[i][j] + f[i - 1][k]) % mod return sum(f[n][j] for j in range(n + 1)) % mod(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !