You are given a string s made of the characters '0', '1' and '!'. Replace every '!' with either '0' or '1'. Each '!' is decided on its own, so two '!' characters may receive different digits.
After the replacements, count how many subsequences of the resulting string equal "01" and how many equal "10". A subsequence is formed by deleting some or none of the characters without changing the order of the rest. For example, "01" appears as a subsequence of "001" twice, using indices (0, 2) and (1, 2).
Return the smallest possible total number of "01" and "10" subsequences over all ways to replace the '!' characters.
Function Signature
def min_subsequences(s: str) -> int:
...
Rules
-
A subsequence is identified by its pair of indices
(i, j)
with
i < j
. Occurrences at different index pairs count separately, even though they spell the same string.
-
Every
'!'
must be replaced. Characters that are already
'0'
or
'1'
stay as they are.
-
Return the minimum total as an integer. For long strings it can exceed the 32-bit range.
Constraints
-
1 <= len(s) <= 10^5
-
Each
s[i]
is
'0'
,
'1'
or
'!'
Examples
Input: s = "0!1"
Output: 2
Replacing '!' with '0' gives "001", which has two "01" subsequences (indices (0, 2) and (1, 2)) and no "10". Replacing it with '1' gives "011", which also has two "01" subsequences and no "10", so the minimum is 2.
Input: s = "!0!1!"
Output: 4
One optimal result is "00010". The '1' at index 3 has three zeros before it (three "01" subsequences) and one zero after it (one "10" subsequence), for a total of 4. No other replacement gives less.
Input: s = "0!1111"
Output: 5
Replacing '!' with '1' gives "011111", where the single zero comes before five ones: five "01" subsequences and no "10". Replacing it with '0' gives "001111", where each of the four ones follows two zeros, for a total of 8.