Construct Smallest Number From DI String - Problem
You are given a 0-indexed string pattern of length n consisting of the characters 'I' meaning increasing and 'D' meaning decreasing.
A 0-indexed string num of length n + 1 is created using the following conditions:
numconsists of the digits'1'to'9', where each digit is used at most once.- If
pattern[i] == 'I', thennum[i] < num[i + 1]. - If
pattern[i] == 'D', thennum[i] > num[i + 1].
Return the lexicographically smallest possible string num that meets the conditions.
Input & Output
Example 1 — Basic Decreasing-Increasing
$
Input:
pattern = "DI"
›
Output:
"213"
💡 Note:
For pattern "DI", we need num[0] > num[1] (D) and num[1] < num[2] (I). Using digits [1,2,3], the arrangement "213" satisfies: 2 > 1 (D) and 1 < 3 (I).
Example 2 — All Increasing
$
Input:
pattern = "III"
›
Output:
"1234"
💡 Note:
Pattern "III" means all positions should be increasing. The lexicographically smallest arrangement is "1234": 1 < 2 < 3 < 4.
Example 3 — All Decreasing
$
Input:
pattern = "DDI"
›
Output:
"3214"
💡 Note:
Pattern "DDI" needs two decreasing positions followed by increasing. Starting with [1,2,3,4], reverse the D-segment [1,2,3] to get [3,2,1,4], giving "3214".
Constraints
- 1 ≤ pattern.length ≤ 8
- pattern contains only characters 'I' and 'D'
Visualization
Tap to expand
Understanding the Visualization
1
Input
Pattern string with 'D' (decreasing) and 'I' (increasing) characters
2
Process
Use stack to handle D-sequences, pop on I or end
3
Output
Lexicographically smallest number string satisfying all constraints
Key Takeaway
🎯 Key Insight: Stack naturally handles decreasing sequences while maintaining lexicographic optimality
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code