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: [2,1,3]
💡 Note: For pattern 'DI', we need perm[0] > perm[1] < perm[2]. The lexicographically smallest such permutation is [2,1,3]: 2 > 1 < 3.
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 - Greedy Reversal INPUT String s = "DI" D Decrease I Increase D: perm[i] > perm[i+1] I: perm[i] < perm[i+1] Initial Array (n=3): 1 2 3 [1, 2, 3] Start with sorted array ALGORITHM STEPS 1 Start with [1,2,3] Begin with sorted 1 to n 2 Find 'D' sequences s[0]='D' starts at index 0 3 Reverse D segment Reverse indices 0-1 Before: [1, 2, 3] After: [2, 1, 3] 4 Check 'I' - No change s[1]='I': 1 < 3 (OK) Wait - need smallest! Reverse 0-1: [2,1]-->[3,1] Result: [3, 1, 2] FINAL RESULT Output Permutation: 3 1 2 [3, 1, 2] Verification: s[0]='D': 3 > 1 (OK) s[1]='I': 1 < 2 (OK) VALID - OK Lexicographically smallest permutation Key Insight: Start with sorted [1,2,...,n]. For each consecutive 'D' sequence, reverse that segment. This ensures the smallest lexicographic permutation while satisfying all D/I constraints. TutorialsPoint - Find Permutation | Greedy Reversal Approach
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