KatInterview

Largest Number With Even Counts of Both Digits

Greedy & IntervalsAuto-graded · 25 test cases
MediumAuto-gradedGreedy & Intervalsgreedystringstack

Last 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:

  1. The number of '1' characters kept is even (zero counts as even).
  2. The number of '2' characters kept is even (zero counts as even).
  3. 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 s is '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.