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:

  • num consists of the digits '1' to '9', where each digit is used at most once.
  • If pattern[i] == 'I', then num[i] < num[i + 1].
  • If pattern[i] == 'D', then num[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
Construct Smallest Number From DI StringInput Pattern:DIDecreasingIncreasingProcessing:Use digits 1,2,3 for pattern length 2Stack approach handles D-sequencesPop on I to reverse decreasing partsOutput Number:2132>1D1<3IResult: "213"Constraints satisfied: 2 > 1 (D) and 1 < 3 (I)Lexicographically smallest valid arrangement
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
Asked in
Google 25 Amazon 18 Microsoft 12 Facebook 8
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