KatInterview

Maximum Number With Even Counts of Ones and Twos

Greedy & IntervalsAuto-graded · 28 test cases
MediumAuto-gradedGreedy & Intervalsgreedystringssubsequence

Last updated

Delete characters from a string of 1s and 2s so both digit counts are even, and return the largest possible number. Tests greedy subsequence construction with count constraints.

You are given a string num_str made up only of the characters '1' and '2'. It is the decimal form of a positive integer.

You may remove any number of characters from it, including none. The characters you keep stay in their original left-to-right order. You cannot change or reorder them.

The string you end up with must satisfy both rules:

  1. It contains an even number of '1' characters.
  2. It contains an even number of '2' characters.

Return the string that represents the largest integer among all strings you can end up with that satisfy both rules.

Details

  • Zero counts as even. A result with no '1' is fine for rule 1, and a result with no '2' is fine for rule 2.
  • Results are compared as integers. No digit is zero, so a longer result is always larger than a shorter one. Two results of the same length compare as ordinary strings, character by character.
  • If no nonempty string satisfies both rules, return the empty string "". For example, num_str = "12" gives "".
  • Different choices of removed positions may produce the same string. Only the resulting string is returned, so the answer is unique.

Constraints

  • 1 <= len(num_str) <= 200000
  • Every character of num_str is '1' or '2'.
  • The number can have up to 200000 digits, so work with strings and do not convert to an integer type.
  • Aim for roughly linear time in len(num_str).

Examples

Example 1

Input: largest_paired_digits('121212')

Output: '2121'

Example 2

Input: largest_paired_digits('2121122')

Output: '221122'

Example 3

Input: largest_paired_digits('1111')

Output: '1111'

Hints

Hint 1

A longer result always beats a shorter one because there are no zeros. Work out how many 1s and how many 2s the best answer must contain.

Hint 2

Once the counts are fixed, the task becomes picking the lexicographically largest subsequence with exactly that many 1s and exactly that many 2s.

Hint 3

Build the answer left to right. Prefer a '2' at its earliest remaining position, but only if enough '1's still remain after it to fill the required 1-count. Otherwise take the earliest '1'. Precompute next-occurrence arrays and a suffix count of 1s for O(1) steps.