Construct Smallest Number From DI String

Medium Topics Company Tags

Build a string of pattern.length + 1 distinct digits chosen from 1 through 9. For each position i, an I in pattern requires the digit at i to be smaller than the next digit; a D requires it to be larger. Return the lexicographically smallest string satisfying every comparison.

Example 1:

Input: pattern = "ID"

Output: "132"

Explanation: The digits in "132" satisfy 1 < 3 and 3 > 2. It is the smallest distinct-digit string satisfying an increase followed by a decrease.

Example 2:

Input: pattern = "DI"

Output: "213"

Explanation: The digits in "213" satisfy 2 > 1 and 1 < 3. The first digit cannot be 1 because the next digit must be smaller, so this is the smallest valid choice.

Example 3:

Input: pattern = "DD"

Output: "321"

Explanation: Two decreases require three strictly decreasing digits. Using the three smallest available digits in decreasing order gives "321".

Constraints:

  • 1 <= pattern.length <= 8
  • Each character is I or D.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.