Leetcode #903: Valid Permutations for DI Sequence
In this guide, we solve Leetcode #903 Valid Permutations for DI Sequence in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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].
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: String, Dynamic Programming, Prefix Sum
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
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)
Python Solution
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
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.