Lexicographically Smallest Digit Sequence from Rise/Fall Pattern
Stacks & QueuesAuto-graded · 26 test casesLast updated
Tests greedy thinking and stack-based reversal to build the smallest digit string satisfying a sequence of increase and decrease constraints.
Problem
You are given a string directions made up of two characters:
'I'meaning the next digit must be greater than the current one (increase).'D'meaning the next digit must be less than the current one (decrease).
Produce the lexicographically smallest string of digits that satisfies every constraint.
Rules
- The output must contain exactly
len(directions) + 1digits. - Every digit is drawn from
1throughlen(directions) + 1, each used exactly once (no repeats, no zeros). - For each index
iindirections:directions[i] == 'I'requiresoutput[i] < output[i + 1]directions[i] == 'D'requiresoutput[i] > output[i + 1]
Among all valid digit strings, return the one that comes first in lexicographic (dictionary) order.
Constraints
1 <= len(directions) <= 8- Every character in
directionsis either'I'or'D'.
Examples
Example 1
Input: smallest_digit_sequence('II')
Output: '123'
Example 2
Input: smallest_digit_sequence('D')
Output: '21'
Example 3
Input: smallest_digit_sequence('I')
Output: '12'
Example 4
Input: smallest_digit_sequence('DID')
Output: '2143'
Example 5
Input: smallest_digit_sequence('IDID')
Output: '13254'
Example 6
Input: smallest_digit_sequence('DDDI')
Output: '43215'
Hints
Hint 1
Think about what a run of consecutive 'D's forces: those positions must be strictly decreasing, so they form a reversed segment of consecutive integers.
Hint 2
Try mentally writing out the digits 1, 2, 3, … in order and asking: when can a digit be committed to the output immediately, and when must it wait? A digit must wait as long as the next character is still 'D'.
Hint 3
A stack lets you accumulate a pending block and flush it in reverse order the moment you hit an 'I' or reach the end of the string. Make sure to flush any remaining digits after processing the last character.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core observation
The output is a permutation of 1, 2, …, n+1 (where n = len(directions)). To be lexicographically smallest, we want the smallest available digits placed as early as possible. The only thing that prevents placing a digit early is a run of 'D' constraints: if positions i through i+k-1 are all 'D', then output positions i through i+k must be strictly decreasing, so the digit at position i must be larger than the k digits that follow it.
Stack-based greedy
Walk positions 0 through n. At each position i, push i + 1 onto a stack. The stack holds a "pending block" of digits that cannot yet be committed because they may need to be reversed.
- When position
iis followed by'I'(oriis the last position), the current descending block ends here. Pop the entire stack into the result. Popping reverses the block, producing the smallest valid decreasing sequence for those slots. - When position
iis followed by'D', keep accumulating.
The final flush at i == n is critical — without it, any trailing 'D' block is dropped.
Trace example
For directions = "DID":
| i | push | directions[i] | action | result so far |
|---|---|---|---|---|
| 0 | 1 | D | hold | |
| 1 | 2 | I | pop 2, 1 | "21" |
| 2 | 3 | D | hold | "21" |
| 3 | 4 | end | pop 4, 3 | "2143" |
Check: 2 > 1 < 4 > 3. Every constraint satisfied.
Why this is valid
Each flushed block contains consecutive integers in decreasing order, satisfying every 'D' inside it. At every block boundary the character is 'I'. The left block ends with its minimum value and the right block starts with its maximum value (which is strictly larger), so every 'I' is satisfied too.
Why this is minimal
For a block covering k+1 slots starting after m digits have already been placed, the largest digit in the block must be at least m + k + 1 (it must exceed k distinct smaller digits below it). The algorithm uses exactly m + k + 1 — the smallest legal choice. The remaining slots are then forced to m+k, m+k-1, …, m+1, the smallest values that form a valid decreasing run. Being optimal at every block left-to-right yields the global lexicographic minimum.
Complexity
- Time: O(n) — each digit is pushed once and popped once.
- Space: O(n) — for the stack and output buffer.
This is asymptotically optimal since the output itself has n+1 characters.
Edge cases
directions | Output | Reason |
|---|---|---|
"I" | "12" | Single increase; no reversal needed |
"D" | "21" | Single decrease; block of size 2 reversed |
"III…" | "123…" | Every digit flushed immediately |
"DDD…" (length 8) | "987654321" | Everything held until the end, then reversed |
def smallest_digit_sequence(directions: str) -> str:
result = []
stack = []
for i in range(len(directions) + 1):
stack.append(str(i + 1))
# Flush when we hit an increase constraint or reach the final position.
if i == len(directions) or directions[i] == 'I':
while stack:
result.append(stack.pop())
return ''.join(result)