KatInterview

Lexicographically Smallest Digit Sequence from Rise/Fall Pattern

Stacks & QueuesAuto-graded · 26 test cases
MediumAuto-gradedStacks & Queuesgreedystackstrings

Last 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

  1. The output must contain exactly len(directions) + 1 digits.
  2. Every digit is drawn from 1 through len(directions) + 1, each used exactly once (no repeats, no zeros).
  3. For each index i in directions:
    • directions[i] == 'I' requires output[i] < output[i + 1]
    • directions[i] == 'D' requires output[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 directions is 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.