Valid Permutations for DI Sequence - Problem
Valid Permutations for DI Sequence

You're given a string s of length n containing only two characters:
  • 'D' means decreasing - the next number should be smaller
  • 'I' means increasing - the next number should be larger

Your task is to find how many valid permutations of numbers [0, 1, 2, ..., n] can satisfy this sequence pattern.

A permutation perm is valid if:
  • When s[i] == 'D', then perm[i] > perm[i+1]
  • When s[i] == 'I', then perm[i] < perm[i+1]

For example, if s = "DI", we need a 3-number permutation where the first pair decreases and the second pair increases.

Goal: Return the count of valid permutations modulo 109 + 7.

Input & Output

example_1.py — Basic DI sequence
$ Input: s = "DI"
Output: 2
💡 Note: For sequence "DI" with numbers [0,1,2], we need first > second and second < third. Valid permutations are: [1,0,2] (1>0 ✓, 0<2 ✓) and [2,0,1] (2>0 ✓, 0<1 ✓). Total: 2 valid permutations.
example_2.py — Single character
$ Input: s = "D"
Output: 1
💡 Note: For sequence "D" with numbers [0,1], we need first > second. Valid permutations: [1,0]. Only 1 valid permutation.
example_3.py — Increasing sequence
$ Input: s = "I"
Output: 1
💡 Note: For sequence "I" with numbers [0,1], we need first < second. Valid permutations: [0,1]. Only 1 valid permutation.

Constraints

  • 1 ≤ s.length ≤ 200
  • s[i] is either 'D' or 'I'
  • Result should be returned modulo 109 + 7

Visualization

Tap to expand
Valid Permutations for DI Sequence INPUT String s = "DI" D I i=0 i=1 D: Decrease (perm[i] > perm[i+1]) I: Increase (perm[i] < perm[i+1]) Numbers: [0, 1, 2] Pattern needed: ? D ? I ? ALGORITHM STEPS 1 DP Table Setup dp[i][j] = permutations ending at position i with value j 2 Initialize Base dp[0][j] = 1 for all j in [0,n] 3 Fill DP Table If 'D': sum values > j If 'I': sum values < j 4 Sum Final Row Answer = sum of dp[n][*] DP Table for "DI": j: 0 1 2 i=0 1 1 1 i=1 2 1 0 i=2 0 2 3 = 5 FINAL RESULT 5 Valid Permutations: [1, 0, 2] - OK [2, 0, 1] - OK [2, 1, 0] - NO [1, 0, 2] - OK All valid: [1,0,2], [2,0,1], [2,1,0] is invalid (I,I pattern) Example: [2,0,1] 2 > 0 (D) -- OK 0 < 1 (I) -- OK Output: 5 Key Insight: Use Dynamic Programming where dp[i][j] represents the count of valid permutations for the first i+1 positions where position i contains the j-th smallest remaining number. For 'D', sum larger values; for 'I', sum smaller values. Use prefix sums to optimize from O(n^3) to O(n^2). Apply modulo 10^9 + 7 to handle large counts. TutorialsPoint - Valid Permutations for DI Sequence | Optimal DP Solution
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 15
42.0K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen