You are given an encoded string s made of lowercase English letters and the digits 1 to 9. Decode it by expanding every digit: a letter immediately followed by a digit d is written d times, and a letter not followed by a digit is written once. The digits themselves are not part of the decoded string.
From the decoded string, return the lexicographically smallest subsequence that contains every distinct letter of the decoded string exactly once.
For example, s = "a2b1c1" decodes to "aabc", and the answer is "abc".
Function Signature
def expand_string(s: str) -> str:
...
Rules
-
A digit always applies to the letter just before it. Counts are single digits from 1 to 9.
-
The result must be a subsequence of the decoded string, so its letters keep their relative order from that string. Rearranging is not allowed.
-
Lexicographic order compares strings letter by letter with
'a' < 'b' < ... < 'z'
. Every candidate has the same length (the number of distinct letters), so the first differing letter decides.
Constraints
-
1 <= len(s) <= 10^4
-
s
consists of lowercase English letters and the digits
1
to
9
.
-
Every digit in
s
is immediately preceded by a lowercase letter.
-
The decoded string has length at most
10^5
.
Examples
Input: s = "a2b1c1"
Output: "abc"
The decoded string is "aabc". Its distinct letters are a, b and c, and "abc" takes them in the order they appear, which is also alphabetical.
Input: s = "c1b2a3"
Output: "cba"
The decoded string is "cbbaaa". The only 'c' is at index 0, so nothing can come before it, and every 'b' comes before every 'a'. That leaves "cba" as the only subsequence with each letter once.
Input: s = "c2ba2cd"
Output: "bacd"
The decoded string is "ccbaacd". The only 'b' is at index 2 and both 'a' come after it, so the answer starts with 'c' or 'b'. Taking the 'c' at index 5 gives "bacd", which is smaller than the other candidate, "cbad".