Construct Smallest Number From DI String

Medium

Description

You are given a string pattern of I's and D's: I means the next digit is greater (increase), D means the next digit is smaller (decrease). Return the lexicographically smallest possible string of digits 1-9 without repeating.

Examples

Input:pattern = "IIIDIDDD"
Output:"123549876"
Explanation:

Smallest valid arrangement.

Input:pattern = "a"
Output:"123549876"
Explanation:

Edge case with a single character.

Input:pattern = "DDD"
Output:4321
Explanation:

With all decreasing pattern, starting with the smallest possible digit that allows for 3 more decreasing digits. Starting with 4, this gives 4>3>2>1, which uses digits 1-4 and satisfies all 'D' constraints while being lexicographically smallest.

Constraints

  • 1 ≤ pattern.length ≤ 8

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!