The Construct Smallest Number From DI String interview question gives you a pattern string of length n consisting of 'I' (Increasing) and 'D' (Decreasing). You need to construct the lexicographically smallest string of length n+1 using digits '1'-'9' (each digit at most once) that follows the pattern.
Goldman Sachs and Google use the Construct Smallest Number From DI String coding problem to test greedy thinking and stack manipulation. While it can be solved with backtracking, the interviewer is usually looking for an O(N) greedy or stack-based approach that demonstrates a higher level of algorithmic efficiency.
This problem follows the Backtracking, Stack, Greedy interview pattern. The stack-based greedy solution is particularly elegant:
Pattern: "IDID"
This ensures that whenever we need to decrease, we reverse the order of the digits we just collected, which naturally provides the smallest possible values for the increasing sections.
Problems involving "Increasing/Decreasing" patterns in strings are often solvable by a simple "Stack and Reverse" logic. If you need to reverse a trend, a stack is the most natural tool to hold the elements until the trend shifts.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Check if a Parentheses String Can Be Valid | Medium | Solve | |
| Minimum Insertions to Balance a Parentheses String | Medium | Solve | |
| Maximum Score From Removing Substrings | Medium | Solve | |
| Minimum Add to Make Parentheses Valid | Medium | Solve | |
| Minimum Additions to Make Valid String | Medium | Solve |