Maximum Even-Frequency Subsequence of Ones and Twos
Medium · Coding & Algorithms · Software Engineer · HR Screen
Problem Statement
Given a non-empty string digits composed exclusively of the characters '1' and '2', you may erase any subset of characters (including none) while keeping the remaining characters in their original left-to-right sequence. Return the string representing the greatest positive base-10 integer among all valid subsequences that satisfy both parity rules:
- The total count of
'1'in the kept string is even (0, 2, 4, ...). - The total count of
'2'in the kept string is even (0, 2, 4, ...).
def largest_even_count_number(digits: str) -> str:
Additional rules:
- Zero occurrences of a character counts as an even frequency (for example, a string containing zero
'1's and four'2's is valid). - Because
'0'never appears, any longer valid string represents a strictly greater integer than any shorter valid string; among valid strings of identical length, standard lexicographical order determines the larger integer. - If every valid subsequence is empty (such as when
digitsis"1","2","12", or"21"), return"".
Examples
Example 1
Input: digits = "12121121"
Output: "212111"
The input has five '1's and three '2's, both odd, so at least one '1' and one '2' must be erased, capping the result at length 6. Removing the '1' at index 0 and the '2' at index 6 leaves "212111" (four '1's and two '2's), which starts with "212..." and beats every other valid 6-digit subsequence.
Example 2
Input: digits = "2122112"
Output: "222112"
There are three '1's (odd) and four '2's (even), so we drop one '1' and keep every '2'. Erasing the '1' at index 1 lets the '2's at indices 2 and 3 shift left to yield "222112", whereas erasing either later '1' (at index 4 or 5) leaves "212212".
Example 3
Input: digits = "2222"
Output: "2222"
There are zero '1's and four '2's. Since both 0 and 4 are even, no characters need to be removed.
Constraints
1 <= len(digits) <= 200,000- Every character in
digitsis'1'or'2'. - Because
digitscan represent a 200,000-digit integer, operate directly on strings without converting the full number to an integer type; aim forO(len(digits))time.
Step-by-step walkthrough
Understand the rules and how to compare giant numbers
We are given a string
digitsmade only of'1'and'2'(up to 200,000 characters). We want to delete zero or more characters without reordering the rest — keeping a subsequence, meaning characters left over in their original left-to-right order — so that:- The count of
'1's in the remaining string is even (0, 2, 4, ...). - The count of
'2's in the remaining string is even (0, 2, 4, ...).
Among all valid subsequences, we must return the one that represents the largest positive integer, or
""if no nonempty valid string exists.Because
digitscan have 200,000 digits, converting to an integer (int(digits)) is forbidden and would fail in Python. Fortunately, there are no'0'digits anywhere in the string, so comparing two positive numbers as strings is simple:- More digits always wins: any 5-digit number of
1s and2s (at least11111) beats any 4-digit number (at most2222). - Same number of digits: compare left to right at the first index where they differ (lexicographical order, i.e., dictionary order). Whichever string has
'2'instead of'1'at that first differing spot is the larger integer.
- The count of
Why brute force is too slow
A direct check tries all
2^npossible subsets of positions, keeps the ones where both counts are even, and picks the best string:def brute_force(digits: str) -> str: n = len(digits) best = "" for mask in range(1 << n): kept = [digits[i] for i in range(n) if (mask >> i) & 1] candidate = "".join(kept) if candidate.count("1") % 2 == 0 and candidate.count("2") % 2 == 0: if len(candidate) > len(best) or ( len(candidate) == len(best) and candidate > best ): best = candidate return bestChecking
2^nsubsets works only up to aroundn = 15(useful for testing!), whereasn = 200,000requires a linearO(n)pass.Key insight 1: the best length is completely forced
Because longer numbers always beat shorter ones, we want to delete as few characters as possible to make both counts even:
- If
ones_countis already even, we delete zero'1's. Ifones_countis odd, we must delete at least one'1', and deleting exactly one'1'makes the count even (ones_count - 1). Deleting 3 or 5'1's would only shrink the number by two or more digits, which always loses! - By the exact same logic, we delete zero
'2's iftwos_countis even, and exactly one'2'iftwos_countis odd.
If that leaves 0 characters (for example
"1","2","12", or"21"), no nonempty valid string exists and we return"". Otherwise, every best candidate has the exact same length, so we only need to pick which single'1'(whenones_countis odd) and which single'2'(whentwos_countis odd) to drop.- If
Key insight 2: drop the first `'1'` and the last `'2'`
Suppose
ones_countis odd, so we must drop one'1'. Deleting a character pulls every character to its right one slot to the left (into a higher place value). Look at"2122112", which has'1's at indices1,4, and5:Original: 2 1 2 2 1 1 2 ^ ^ ^ Drop first '1' (i=1): 2 2 2 1 1 2 <- '2' shifts into index 1! Drop later '1' (i=4): 2 1 2 2 1 2 <- index 1 stays '1' (smaller) Drop later '1' (i=5): 2 1 2 2 1 2 <- index 1 stays '1' (smaller)Whenever a
'2'appears anywhere after the'1'we delete, the very first'2'after it shifts left by one spot, turning a'1'into a'2'! The earlier we make that upgrade happen, the higher its place value. (If there are no'2's after any'1', all'1's sit in a single block at the end like"22111", so deleting any'1'gives the exact same"2211".) Therefore, deleting the leftmost'1'(digits.index("1")) is always optimal.Now flip the logic when
twos_countis odd and we must drop one'2'. Look at"21221", which has'2's at indices0,2, and3:Original: 2 1 2 2 1 ^ ^ ^ Drop first '2' (i=0): 1 2 2 1 <- pulls '1' into index 0 (hurts!) Drop last '2' (i=3): 2 1 2 1 <- keeps '2' at index 0 and index 2 (wins!)Deleting an early
'2'pulls the next'1'after it one slot left, downgrading a'2'to a'1'. We want that downgrade to happen as far right as possible — or not at all if no'1'follows it. Therefore, deleting the rightmost'2'(digits.rindex("2")) is always optimal.Why both rules still work together when both counts are odd
What if both
ones_countandtwos_countare odd, so we drop one'1'and one'2'? Do the two choices interfere with each other?No! Take any pair of deletions
(one_pos, two_pos):- Hold
two_posfixed and look at the string withdigits[two_pos]already removed. Removing a'2'never removes any'1', so the original leftmost'1'is still the leftmost'1'of this string. By our first rule, replacingone_poswithdigits.index("1")makes the result at least as large. - Now hold
digits.index("1")fixed and look at the string with that'1'removed. Removing a'1'never removes any'2', so the original rightmost'2'is still the rightmost'2'. By our second rule, replacingtwo_poswithdigits.rindex("2")again makes the result at least as large.
So dropping
digits.index("1")anddigits.rindex("2")beats (or ties) every other pair!- Hold
Trace Example 1 step by step
Let's trace
digits = "12121121":Index: 0 1 2 3 4 5 6 7 Character: 1 2 1 2 1 1 2 1 1. Count digits: ones_count = 5 (odd) -> drop_one_idx = digits.index("1") = 0 twos_count = 3 (odd) -> drop_two_idx = digits.rindex("2") = 6 2. Scan left to right, skipping indices 0 and 6: index 0 ('1') -> skip index 1 ('2') -> keep index 2 ('1') -> keep index 3 ('2') -> keep index 4 ('1') -> keep index 5 ('1') -> keep index 6 ('2') -> skip index 7 ('1') -> keep Result: "212111"Complete solution
We use
-1as a sentinel index meaning "nothing to delete for this digit", since valid string indices start at0. Notice that whenones_countis odd,ones_count >= 1, sodigits.index("1")is guaranteed to find a'1'without raisingValueError(and likewise fordigits.rindex("2")).from typing import Any, Dict, List, Optional, Set, Tuple def largest_even_count_number(digits: str) -> str: # Phase 1: Count how many '1's and '2's appear in the input string. ones_count = digits.count("1") twos_count = digits.count("2") # Phase 2: Choose at most one '1' index and one '2' index to delete. # Sentinel value -1 means "count is already even, so delete nothing". drop_one_idx = -1 drop_two_idx = -1 if ones_count % 2 == 1: # Why first '1': removing the leftmost '1' lets the earliest following '2' # shift one spot left into a higher place-value position. drop_one_idx = digits.index("1") if twos_count % 2 == 1: # Why last '2': removing an earlier '2' would pull a smaller '1' left; # removing the rightmost '2' keeps every earlier '2' in its high position. drop_two_idx = digits.rindex("2") # Phase 3: Build the kept subsequence in one O(n) pass. # kept_digits: list of single-character strings ('1' or '2') in original order. kept_digits: List[str] = [] for i, ch in enumerate(digits): if i != drop_one_idx and i != drop_two_idx: kept_digits.append(ch) return "".join(kept_digits)✅ Submit now — all tests should pass.
Intuition & how it works
Imagine a row of tiles stamped 1 and 2 spelling out a huge number on a table. Whenever you slide one tile out, every tile to its right slides one slot left into a higher place-value column (for instance, from the tens place into the hundreds place). First, because there are no 0 tiles, keeping more tiles always makes a bigger number (1111 beats 222 every time). That means we should delete at most one 1 (only when the number of 1s has odd parity, meaning it is not divisible by 2) and at most one 2 (only when the number of 2s is odd). Second, among equal-length results, we want larger digits as far left as possible (lexicographical order, comparing left to right at the first mismatch): pulling out the leftmost 1 lets the next 2 slide left as early as possible, whereas pulling out the rightmost 2 protects all earlier 2s from sliding a 1 into their spot.
A naive approach tries every possible subsequence (a string formed by deleting some characters without changing the order of the rest) or tries deleting every pair of indices (i, j) and comparing the resulting strings. Checking all subsets takes 2^n work, and even checking every (i, j) pair and building a string of length n takes O(n^3) work — around 8 * 10^15 operations when n = 200,000, which would take days instead of milliseconds. Worse, converting the string to an int fails outright because a 200,000-digit integer far exceeds standard integer limits and Python's string-to-int safety cap.
Let's walk through a tiny concrete example: digits = "12212".
1. Count each digit: there are two '1's (even) and three '2's (odd).
2. Because '1' already has an even count, we keep all '1's (drop_one_idx = -1, using -1 as a sentinel value — a special out-of-range marker meaning "skip nothing").
3. Because '2' has an odd count, we drop the rightmost '2' at index 4 (drop_two_idx = 4).
4. Reading indices 0..3 leaves "1221" (two '1's, two '2's). Compare that with dropping the first '2' at index 1 ("1212") or index 2 ("1212"): "1221" wins at index 2!
Complexity
- Time: O(n), where
n = len(digits). We scan the string twice withcount, scan at most twice withindexandrindex, and make one final left-to-right pass to collectkept_digitsand join it into a string — a constant number ofO(n)passes. - Space: O(n) for
kept_digitsand the returned string of length up ton. Aside from building the output itself, we only store four integer variables (O(1)auxiliary space).
Edge cases
- Single digit (
"1"or"2"): one digit has count 1 (odd) and the other has count 0 (even). Dropping the single digit leaves"", matching the empty-string convention. - One of each digit (
"12"or"21"): both counts are 1 (odd), so both indices are dropped and""is returned. - Already valid (
"2222","2112"): zero is an even count, so bothdrop_one_idxanddrop_two_idxremain-1and the entire input string is returned unchanged. - Only one distinct digit with odd count (
"222"):'1'has count 0 (even) and'2'has count 3 (odd), returning"22". - All
'1's grouped after all'2's ("22111"):digits.index("1")picks index2, leaving"2211"(deleting index3or4yields the exact same string). - Maximum size (
n = 200,000): five linear passes in C and Python finish in a few milliseconds without ever converting toint.
Common mistakes
- Deleting extra digits (such as dropping an entire run of
'1's): any valid subsequence that deletes 3'1's instead of 1 is two digits shorter, and a shorter positive number with nonzero digits is always strictly smaller than a longer one. - Dropping the rightmost
'1'or the leftmost'2': that reverses both rules and produces the smallest number of maximum length instead of the largest. - Calling
int(digits)to compare numbers: Python 3.11+ raisesValueError: Exceeds the limit (4300 digits) for integer string conversionon large inputs, and 64-bit integers in other languages overflow past 19 digits. - Returning
"0"when no nonempty subsequence works:'0'does not exist indigits, and the problem explicitly specifies returning"". - Repeated string slicing inside a loop: building the output once with
"".join(kept_digits)isO(n), whereas repeatedly slicing inside nested loops becomesO(n^2)orO(n^3).
Alternative approaches
- Single-pass counting and position tracking: instead of calling
count,index, andrindexseparately, one loop overenumerate(digits)can computeones_count,twos_count,first_one, andlast_twosimultaneously, followed by up to two slices to skip the dropped positions. Both versions areO(n)time andO(n)output space; the built-in string methodscount,index, andrindexrun in fast C loops and are very easy to read. - Prefix-ones counting proof: every string with
Aones andBtwos is uniquely determined by how many'1's appear before each of theBtwos (fewer'1's before a'2'means that'2'sits further left). Dropping the very first'1'decreases that count for as many'2's as possible, and dropping the very last'2'discards the'2'that had the most'1's in front of it.
Follow-up questions
- How does the strategy change if you must return the smallest valid positive integer instead of the largest? It depends on whether we want the smallest among maximum-length results or the smallest nonempty number overall. Among maximum-length valid results, we flip both choices: delete the last
'1'(digits.rindex("1")) so'2's stay behind'1's, and delete the first'2'(digits.index("2")) so the earliest following'1'shifts left into a high place value. If any nonempty valid length is allowed, shorter numbers win, so"11"beats"22", which beats any 4-digit number whenever two matching digits exist! - How would you generalize this if each digit's final count had to be divisible by k rather than 2? To maximize length, we must delete
r1 = ones_count % kcopies of'1'andr2 = twos_count % kcopies of'2'. By the same place-value reasoning, we delete the firstr1occurrences of'1'(removing as many'1's as possible from in front of every'2') and the lastr2occurrences of'2'(keeping the'2's that sit earliest in the string), which still runs inO(n)time. - How could you solve this in constant memory if the input string lived in a multi-gigabyte file on disk? Stream the file in two sequential passes using
O(1)RAM. Pass 1 reads character by character while maintainingones_count,twos_count,first_one_idx, andlast_two_idx; Pass 2 streams the file again and writes every character whose byte offset is not one of the (at most two) dropped offsets directly to the output stream.
Follow-up questions
- How does the strategy change if you must return the smallest valid positive integer instead of the largest?
- How would you generalize this if each digit's final count had to be divisible by k rather than 2?
- How could you solve this in constant memory if the input string lived in a multi-gigabyte file on disk?
Similar questions
- Annual Account Balance After Monthly Fee Waivers
- Minimum Deletions to Prevent Consecutive Triples
- Minimum Postponed Debits for Non-Negative Ledger
- Scoped Nested Transactions for a Key-Value Store
- Longest Substring With Uniform Character Counts
- Largest Even-Parity Subsequence of Ones and Twos
More DRW interview questions
- Annual Account Balance After Monthly Fee Waivers Easy
- Expected Target Score for Isotropic Gaussian Throws Hard
- Stopping Time and Absorption Odds for Two Cart Queues Hard Pro
- Conditional Flip Count When HHT Beats HTH Hard Pro
- Prize Collection Odds on a 45-Node Ring Hard Pro
- Minimum Postponed Debits for Non-Negative Ledger Easy Pro
- Scoped Nested Transactions for a Key-Value Store Easy Pro
- Longest Substring With Uniform Character Counts Easy Pro
- Largest Even-Parity Subsequence of Ones and Twos Hard Pro
- Smallest Array Spread Within Three Element Edits Easy Pro