Largest Number With Even Counts of Both Digits
Greedy & IntervalsAuto-graded · 25 test casesLast updated
Delete characters from a string of 1s and 2s so both digit counts are even and the number is largest, testing greedy deletion with parity reasoning.
You are given a string s made up only of the characters '1' and '2'. Read it as a positive decimal integer.
Choose a subsequence of s, obtained by deleting any number of characters (possibly none) without reordering the rest, so that:
- The number of
'1'characters kept is even (zero counts as even). - The number of
'2'characters kept is even (zero counts as even). - Among all subsequences meeting the first two rules, the value of the resulting integer is as large as possible.
Return the chosen subsequence as a string. If the best choice keeps no characters, return the empty string "".
Comparing candidates. Every character is a nonzero digit, so a longer string is always a larger number than a shorter one. Two strings of equal length are compared character by character from the left, and the first position where they differ decides which is larger.
Constraints
1 <= len(s) <= 2 * 10^5- Every character of
sis'1'or'2'. - The expected running time is linear in
len(s).
Examples
Example 1
Input: best_even_count_subsequence('21121')
Output: '2121'
Example 2
Input: best_even_count_subsequence('12122')
Output: '1212'
Example 3
Input: best_even_count_subsequence('12')
Output: ''
Hints
Hint 1
Since every digit is nonzero, a longer result always beats a shorter one. How many characters must you remove at minimum, given the parities of the two counts?
Hint 2
Only the parity of each count matters. You need to remove exactly one '1' if the count of ones is odd, and exactly one '2' if the count of twos is odd. The question is which occurrence to remove.
Hint 3
Removing a smaller digit that sits just before a larger digit raises the number. Scan left to right with a stack and pop a '1' when a '2' arrives, as long as you still owe a removal of '1'. Afterward, spend any leftover removals on the last occurrences from the end.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Length comes first. All digits are nonzero, so the longest valid subsequence always wins. That means we delete as few characters as possible. A count that is already even needs no deletion. A count that is odd needs exactly one deletion of that digit. Deleting more than that only shortens the result without changing parity.
So the digits we owe are:
- one
'1'if the number of ones is odd, - one
'2'if the number of twos is odd.
Choosing which occurrence to delete. Among results of equal length, we want the leftmost difference to favor a larger digit. Deleting a character shifts the next character into its place, so the best deletion is one where a smaller digit is followed by a larger one:
- For a
'1', delete the first'1'that is followed by a'2'. If there is no such'1', all ones form one final block and every choice gives the same string, so deleting the last one is fine. - For a
'2', nothing larger can follow it, so a'2'is never improved by removal. The best choice is the last'2', because earlier removals pull a'1'into an earlier position.
Stack implementation. Scan left to right and maintain a stack of kept characters. When the current character is larger than the stack top and we still owe a deletion of that top digit, pop it and reduce the debt. Then push the current character. This performs the "delete a smaller digit just before a larger one" step as early as possible.
After the scan, any debt left over means no smaller-before-larger opportunity remained for that digit. The stack is then non-increasing in the relevant places, so the best choice is to delete the last occurrences. We walk the stack from the end, skipping characters we still owe, and reverse the result.
Why it is correct
- Minimal deletion count is forced by the length argument.
- Popping a smaller digit before a larger one, as early as possible, is an exchange argument: any other choice of deleted position agrees with this one up to that point and then holds a smaller digit there.
- When no such pair is available, the remaining deletions lie in a trailing non-increasing region, where removing the last occurrence leaves the largest string.
- The two digit types do not interfere. Removing a
'1'does not change which'2'is last, and vice versa.
Complexity
- Time: O(n), since each character is pushed and popped at most once and the final pass is linear.
- Space: O(n) for the stack and the output.
Reference solution
def best_even_count_subsequence(s: str) -> str:
ones = s.count('1')
twos = s.count('2')
owed = {'1': ones % 2, '2': twos % 2}
stack = []
for ch in s:
while stack and stack[-1] < ch and owed[stack[-1]]:
owed[stack.pop()] -= 1
stack.append(ch)
if owed['1'] or owed['2']:
kept = []
for ch in reversed(stack):
if owed[ch]:
owed[ch] -= 1
else:
kept.append(ch)
stack = kept[::-1]
return ''.join(stack)