Ctrl K

Up-Down Digit Code

Medium
A combination lock takes a code made of distinct digits from 1 to 9. Instead of the code itself you have a hint signs: a string of length n made of the letters 'I' and 'D'. The code has n + 1 digits, and for every position i: - if signs[i] == 'I', digit i of the code is smaller than the next one; - if signs[i] == 'D', digit i of the code is larger than the next one. Each digit may be used at most once. Among all codes that fit the hint, return the smallest one as a string (all candidate codes have the same length, so this is the same as the smallest number).
Example 1
signs="IDI" → '1324'

We need a < b > c < d. Put 1 first; the second digit must exceed the third, so the best is 3, then 2, then 4: "1324".

Example 2
signs="DDI" → '3214'

The first three digits fall, so the code cannot start with 1: the smallest choice is "321", followed by 4.

Example 3
signs="I" → '12'
Constraints
  • 1 ≤ len(signs) ≤ 8
  • signs consists only of the letters 'I' and 'D'
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsEvery Letter Once MediumErase Digits for the Smallest Number MediumSmallest Up-Down Sequence MediumBrackets With Wildcards MediumBrackets to Patch In Medium
loading Python…
Input
signs="IDI"
Expected
'1324'

Run checks the first 3 tests in your browser. Submit checks all 72 tests on the server, hidden ones included.