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' if perm[i] < perm[i + 1]
  • s[i] == 'D' if perm[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
DI String Match: Transform Pattern to PermutationInput: s = "IDI"IDIAvailable: [0,1,2,3]low = 0, high = 3Transform0312Output: [0,3,1,2]Verification: 0<3 (I), 3>1 (D), 1<2 (I) ✓
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'
Asked in
Google 15 Microsoft 12 Amazon 8
67.5K Views
Medium Frequency
~15 min Avg. Time
1.8K 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