Maximize a Digit Subsequence with Even Counts of Ones and Twos
Company: DRW
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: HR Screen
Overview: Delete digits while preserving order to maximize a number whose counts of both ones and twos are even, with linear-time handling of long strings.
Read the full DRW Software Engineer interview experience this question came from
Constraints
- 1 <= len(digits) <= 200000.
- Every character of `digits` is `1` or `2`.
- The returned string must be a subsequence of `digits` (the relative order of kept characters is preserved).
- In the returned string the count of `1` must be even and the count of `2` must be even; zero is even.
- If no nonempty valid subsequence exists, return the empty string `""`.
- Return a string; do not convert the whole input to a machine-sized integer.
- The intended solution runs in O(n) time, where n is the input length; O(n) output storage is permitted.
Examples
Input: ('1',)
Expected Output: ''
Explanation: Minimum length: one '1' is an odd count, so it must be deleted and nothing valid and nonempty remains.
Input: ('2',)
Expected Output: ''
Explanation: Minimum length: one '2' is an odd count, so it must be deleted and the result is empty.
Hints
- Every digit is nonzero, so no valid answer has a leading zero: compare candidates by length first and only use lexicographic order to break ties between equally long ones.
- Only the parity of each digit's count can make a string invalid, which pins down exactly how many characters any optimal answer removes.
- The two digit values are not symmetric. Removing a character lets the characters after it shift one place to the left, and whether that helps depends on whether the removed digit is the smaller or the larger one.