Maximum Number With Even Counts of Ones and Twos
Greedy & IntervalsAuto-graded · 28 test casesLast 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:
- It contains an even number of
'1'characters. - 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_stris'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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Step 1: decide the length. Let c1 and c2 be the counts of '1' and '2' in the input. A valid result uses an even number of each digit and cannot use more than exist. So the most it can use is need1 = c1 rounded down to even ones and need2 = c2 rounded down to even twos. That many of each can always be chosen. No digit is zero, so more digits means a larger number. The answer therefore has exactly need1 ones and need2 twos. If both are zero (this happens only for "1", "2", "12", "21"), return "".
Step 2: decide the content. With the length fixed, we want the lexicographically largest subsequence containing exactly need1 ones and need2 twos. Build it left to right, keeping a pointer pos into the input:
- Find the earliest
'2'at indexj >= pos. Take it if some twos are still needed and at leastneed1ones remain strictly afterj. - Otherwise take the earliest
'1'at or afterpos.
Two precomputed arrays make each step O(1): nxt1[i] and nxt2[i] (the next index at or after i holding that digit), and suf1[i] (the number of '1's in s[i:]).
Why it works
- Invariant: the suffix
s[pos:]always holds at leastneed1ones and at leastneed2twos, so the selection can be completed. It holds at the start by the choice ofneed1andneed2. - Taking a
'2': the check onsuf1covers the ones. Sincejis the first'2'in the suffix, at leastneed2 - 1twos remain after it, which is what is still needed. - Taking a
'1': ifneed2 == 0the twos no longer matter, and the earliest'1'leaves the most ones behind. Ifneed2 > 0, the'2'failed the check, so exactlyneed1 - 1ones lie afterj. The earliest'1'is beforejand keeps everything still feasible. - Optimality: among equal-length strings the first differing position decides. The greedy puts a
'2'there whenever any valid completion can. If the earliest'2'fails, later ones fail too, because they have fewer'1's after them. Using the earliest occurrence of the chosen digit leaves the largest remaining suffix, so no option is lost.
Complexity
- Time: O(n), with one counting pass, one backward pass to build the arrays, and at most n greedy steps of O(1) each.
- Space: O(n) for the three helper arrays plus the output.
Reference solution
def largest_paired_digits(num_str: str) -> str:
s = num_str
n = len(s)
c1 = s.count('1')
c2 = n - c1
need1, need2 = c1 - c1 % 2, c2 - c2 % 2
if need1 + need2 == 0:
return ""
# suf1[i]: number of '1's in s[i:]
# nxt1[i], nxt2[i]: first index >= i holding '1' / '2' (n if none)
suf1 = [0] * (n + 1)
nxt1 = [n] * (n + 1)
nxt2 = [n] * (n + 1)
for i in range(n - 1, -1, -1):
if s[i] == '1':
suf1[i] = suf1[i + 1] + 1
nxt1[i] = i
nxt2[i] = nxt2[i + 1]
else:
suf1[i] = suf1[i + 1]
nxt2[i] = i
nxt1[i] = nxt1[i + 1]
out = []
pos = 0
while need1 + need2:
j = nxt2[pos]
if need2 and j < n and suf1[j + 1] >= need1:
out.append('2')
need2 -= 1
else:
j = nxt1[pos]
out.append('1')
need1 -= 1
pos = j + 1
return ''.join(out)