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 String INPUT Pattern String: D index 0 I index 1 Meaning: D = Decreasing (next smaller) I = Increasing (next larger) Available Digits: 1-9 1 2 3 4 5 6 7 8 pattern = "DI" ALGORITHM STEPS 1 Initialize Stack Use stack to handle D sequences 2 Process 'D' at index 0 Push 1 to stack: [1] 3 Process 'I' at index 1 Push 2, pop all: result="21" 4 Final digit Push 3, pop: result="213" Greedy Trace: i=0: D, push 1, stack=[1] i=1: I, push 2, pop all result = "2" + "1" = "21" end: push 3, pop all result = "21" + "3" = "213" FINAL RESULT Smallest Valid Number: 2 pos 0 1 pos 1 3 pos 2 Verification: D: 2 > 1 [OK] I: 1 < 3 [OK] Pattern satisfied! Output: "213" Lexicographically Smallest! Key Insight: Use a stack to reverse sequences of 'D'. When we see 'I' or reach the end, pop all elements. This greedy approach ensures we always use the smallest available digits while satisfying constraints. TutorialsPoint - Construct Smallest Number From DI String | Greedy Approach
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