DI String Match - Problem
DI String Match - Reconstruct a Permutation from Instructions
You're given a string
Rules:
• If
• If
Example: For
• Position 0: 0 < 4 ✓ (I)
• Position 1: 4 > 1 ✓ (D)
• Position 2: 1 < 3 ✓ (I)
• Position 3: 3 > 2 ✓ (D)
Return any valid permutation that matches the pattern.
You're given a string
s of length n containing only characters 'I' (Increase) and 'D' (Decrease). Your task is to construct a permutation of integers from [0, 1, 2, ..., n] that satisfies the given pattern.Rules:
• If
s[i] == 'I', then perm[i] < perm[i+1] (next number should be larger)• If
s[i] == 'D', then perm[i] > perm[i+1] (next number should be smaller)Example: For
s = "IDID", one valid permutation is [0,4,1,3,2]• Position 0: 0 < 4 ✓ (I)
• Position 1: 4 > 1 ✓ (D)
• Position 2: 1 < 3 ✓ (I)
• Position 3: 3 > 2 ✓ (D)
Return any valid permutation that matches the pattern.
Input & Output
example_1.py — Basic Pattern
$
Input:
s = "IDID"
›
Output:
[0,4,1,3,2]
💡 Note:
We need a permutation where positions follow I-D-I-D pattern. Using greedy approach: I→use min(0), D→use max(4), I→use min(1), D→use max(3), last→remaining(2). Verification: 0<4✓, 4>1✓, 1<3✓, 3>2✓
example_2.py — All Increasing
$
Input:
s = "III"
›
Output:
[0,1,2,3]
💡 Note:
All characters are 'I' (increase), so we need strictly increasing sequence. Greedy approach always picks minimum available: 0,1,2,3. This is the natural ascending order.
example_3.py — All Decreasing
$
Input:
s = "DDI"
›
Output:
[3,2,0,1]
💡 Note:
Pattern is D-D-I. Start with max for decreasing: D→3, D→2, I→0 (need room to increase), last→1. Verification: 3>2✓, 2>0✓, 0<1✓
Visualization
Tap to expand
Understanding the Visualization
1
Setup Trail Markers
You have elevation markers 0,1,2,3,4 and path instructions I-D-I-D
2
Smart Placement Strategy
Keep lowest and highest unused markers ready for strategic placement
3
Handle Uphill (I)
When trail goes uphill, use lowest marker to maximize future options
4
Handle Downhill (D)
When trail goes downhill, use highest marker to ensure room for drops
5
Complete the Trail
Place final marker and verify the path follows all requirements
Key Takeaway
🎯 Key Insight: By strategically choosing extreme values (minimum for increases, maximum for decreases), we guarantee that future constraints can always be satisfied, leading to an optimal O(n) solution.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the string, constant work per character
✓ Linear Growth
Space Complexity
O(1)
Only using two pointer variables plus output array
✓ Linear Space
Constraints
- 1 ≤ s.length ≤ 105
- s[i] is either 'I' or 'D'
- The permutation must contain all integers from 0 to n exactly once
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code