Largest Number From a 1-and-2 Digit String With Even Counts of Each Digit
Company: DRW
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: HR Screen
Overview: Given a string of 1s and 2s that represents a positive integer, delete characters so the remaining counts of both digits are even, keeping the original order, and return the largest number that can remain. The problem tests careful case analysis of which digit occurrences to remove and efficient string handling for inputs up to 200,000 characters.
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 represented integer can have up to 200000 digits, far beyond 2^31 - 1 and also beyond the 64-bit range, so digits and the returned value are strings; do not convert them to a numeric type.
- The returned value is a string containing only '1' and '2' characters, and it may be empty.
- Aim for a solution that runs in roughly linear time in len(digits).
Examples
Input: ('1',)
Expected Output: ''
Explanation: Minimum length. One '1' is an odd count, so it must be deleted; no nonempty result qualifies, so the convention returns the empty string.
Input: ('2',)
Expected Output: ''
Explanation: Minimum length with the other digit: the single '2' is an odd count and must go, leaving the empty string.
Hints
- Only the parity of each digit's count matters. Work out what the parity of the number of '1' characters and the parity of the number of '2' characters force you to delete.
- Deleting a single character changes exactly one of the two parities, and since no digit is zero, a longer result always represents a larger integer than a shorter one.
- When you are forced to drop one copy of a digit, every candidate result has the same length, so compare them lexicographically: what follows the dropped copy decides which choice is best.