Watch 10 video solutions for Construct Smallest Number From DI String, a medium level problem involving String, Backtracking, Stack. This walkthrough by NeetCodeIO has 12,082 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
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.pattern[i] == 'I', then num[i] < num[i + 1].pattern[i] == 'D', then num[i] > num[i + 1].Return the lexicographically smallest possible string num that meets the conditions.
Example 1:
Input: pattern = "IIIDIDDD" Output: "123549876" Explanation: At indices 0, 1, 2, and 4 we must have that num[i] < num[i+1]. At indices 3, 5, 6, and 7 we must have that num[i] > num[i+1]. Some possible values of num are "245639871", "135749862", and "123849765". It can be proven that "123549876" is the smallest possible num that meets the conditions. Note that "123414321" is not possible because the digit '1' is used more than once.
Example 2:
Input: pattern = "DDD" Output: "4321" Explanation: Some possible values of num are "9876", "7321", and "8742". It can be proven that "4321" is the smallest possible num that meets the conditions.
Constraints:
1 <= pattern.length <= 8pattern consists of only the letters 'I' and 'D'.Problem Overview: You are given a string consisting of 'D' (decreasing) and 'I' (increasing). The goal is to build the smallest possible number using digits 1–9 without repetition such that the digits follow the pattern. For example, if the pattern contains D, the next digit must be smaller than the previous digit. The challenge is enforcing the pattern while keeping the overall number lexicographically smallest.
Approach 1: Greedy Approach with Stack (O(n) time, O(n) space)
This approach processes the pattern from left to right and uses a stack to temporarily store digits. Push numbers sequentially starting from 1. Whenever you encounter an 'I' or reach the end of the pattern, pop all elements from the stack and append them to the result. This reversal ensures that segments of 'D' automatically produce decreasing sequences while still using the smallest available digits. The key insight: delaying output until an increasing boundary lets you reverse the necessary portion to satisfy multiple consecutive D constraints.
This greedy strategy guarantees the smallest valid number because digits are assigned in increasing order and only reversed when the pattern forces a decrease. Each digit is pushed and popped once, making the algorithm linear. This is the most common interview solution and works well for patterns with long decreasing runs.
Approach 2: Construct from Left to Right (Greedy Pattern Handling) (O(n) time, O(1) extra space)
Another strategy builds the answer array directly while scanning the pattern. Start by filling the digits sequentially. When a 'D' segment appears, identify the full length of that decreasing run and reverse the corresponding portion of the result. For example, if the pattern contains DDD, the next four digits must form a decreasing sequence, so the digits assigned to that segment are reversed after placement.
This method relies on the same greedy observation: the smallest digits should appear as early as possible, but decreasing runs must be reversed to satisfy ordering constraints. Instead of using a stack, the algorithm manipulates segments directly. The logic stays simple and uses constant auxiliary memory.
Approach 3: Backtracking (O(9! ) worst case, O(n) space)
A brute-force method uses backtracking to generate permutations of digits 1–9 and check whether each permutation satisfies the DI pattern. Because the goal is the smallest valid number, the search can stop as soon as a valid candidate appears. While conceptually straightforward, the factorial search space makes this impractical for interviews. It mainly helps illustrate the constraint structure before applying a greedy optimization.
Recommended for interviews: The greedy stack solution is the expected answer. It demonstrates understanding of pattern constraints and efficient use of a greedy strategy with a stack. Explaining the brute-force backtracking approach first shows reasoning about the search space, but implementing the O(n) greedy method signals strong problem-solving skills.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Backtracking (Permutation Search) | O(9!) | O(n) | Understanding the constraint structure or building intuition before optimization |
| Greedy with Stack | O(n) | O(n) | Interview-friendly approach; handles long decreasing sequences cleanly |
| Construct from Left to Right (Segment Reversal) | O(n) | O(1) | When minimizing auxiliary structures and working directly on the result array |