DI String Match - Problem
A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where:
s[i] == 'I'ifperm[i] < perm[i + 1]s[i] == 'D'ifperm[i] > perm[i + 1]
Given a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them.
Input & Output
Example 1 — Basic Pattern
$
Input:
s = "IDID"
›
Output:
[0,4,1,3,2]
💡 Note:
For 'I', use smallest available (0). For 'D', use largest (4). Continue: 'I'→1, 'D'→3, final→2. Result: 0<4, 4>1, 1<3, 3>2 matches IDID.
Example 2 — All Increasing
$
Input:
s = "III"
›
Output:
[0,1,2,3]
💡 Note:
All 'I' means strictly increasing sequence. Use numbers 0,1,2,3 in order: 0<1<2<3 matches III.
Example 3 — All Decreasing
$
Input:
s = "DDI"
›
Output:
[3,2,0,1]
💡 Note:
For 'D', use largest available. 'D'→3, 'D'→2, 'I'→0, final→1. Result: 3>2>0<1 matches DDI.
Constraints
- 1 ≤ s.length ≤ 105
- s consists of 'I' and 'D' only
Visualization
Tap to expand
Understanding the Visualization
1
Input Pattern
DI string specifies increase/decrease relationships
2
Greedy Assignment
Use extreme values to maximize flexibility
3
Valid Permutation
Resulting array satisfies all DI constraints
Key Takeaway
🎯 Key Insight: Use greedy assignment with two pointers - smallest for 'I', largest for 'D'
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code