Find Permutation - Problem

A permutation perm of n integers containing all integers from 1 to n can be represented as a string s of length n - 1 where:

  • s[i] == 'I' if perm[i] < perm[i + 1] (Increasing)
  • s[i] == 'D' if perm[i] > perm[i + 1] (Decreasing)

Given a string s, reconstruct the lexicographically smallest permutation perm and return it.

Lexicographically smallest means the permutation that would appear first in dictionary order.

Input & Output

Example 1 — Basic Pattern
$ Input: s = "DI"
Output: [3,1,2]
💡 Note: For pattern 'DI', we need perm[0] > perm[1] < perm[2]. The lexicographically smallest such permutation is [3,1,2]: 3 > 1 < 2.
Example 2 — All Increasing
$ Input: s = "III"
Output: [1,2,3,4]
💡 Note: For pattern 'III', we need all increasing: perm[0] < perm[1] < perm[2] < perm[3]. The answer is simply [1,2,3,4].
Example 3 — All Decreasing
$ Input: s = "DD"
Output: [3,2,1]
💡 Note: For pattern 'DD', we need all decreasing: perm[0] > perm[1] > perm[2]. The lexicographically smallest is [3,2,1].

Constraints

  • 1 ≤ s.length ≤ 105
  • s[i] is either 'I' or 'D'

Visualization

Tap to expand
Find Permutation: Pattern 'DI' → Lexicographically Smallest PermutationInput PatternDIs = "DI"Initial Sorted Array123[1,2,3]transformFinal Result312[3,1,2]reverse DPattern Verification3 > 1 (D) ✓ and 1 < 2 (I) ✓Lexicographically smallest valid permutation!
Understanding the Visualization
1
Input
Pattern string 'DI' representing decrease-increase
2
Process
Start with sorted array and reverse D segments
3
Output
Lexicographically smallest valid permutation
Key Takeaway
🎯 Key Insight: Start with sorted order and reverse only the segments that need to be decreasing
Asked in
Google 25 Facebook 18 Amazon 15 Microsoft 12
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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