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 - Greedy Stack-Based INPUT String s = "IDID" I D I D 0 1 2 3 I = Increase (perm[i] < perm[i+1]) D = Decrease (perm[i] > perm[i+1]) Available: [0,1,2,3,4] n = 4, need n+1 = 5 numbers Two Pointers: low = 0, high = 4 0 ... 4 low high ALGORITHM STEPS 1 s[0]='I' --> use low Add 0, low becomes 1 0 2 s[1]='D' --> use high Add 4, high becomes 3 4 3 s[2]='I' --> use low Add 1, low becomes 2 1 4 s[3]='D' --> use high Add 3, high becomes 2 3 5 End: low == high Add remaining: 2 2 Building Result: [0, 4, 1, 3, 2] OK I: pick smallest | D: pick largest FINAL RESULT Output Permutation: 0 4 1 3 2 i=0 i=1 i=2 i=3 i=4 Verification: 0 < 4 I OK 4 > 1 D OK 1 < 3 I OK 3 > 2 D OK Pattern: "IDID" 0 4 1 3 2 Key Insight: For 'I' (Increase): Use the smallest available number (low) so the next number can be larger. For 'D' (Decrease): Use the largest available number (high) so the next number can be smaller. This greedy approach guarantees a valid permutation in O(n) time with O(1) extra space. TutorialsPoint - DI String Match | Greedy Two-Pointer Approach
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