Problem · String
Largest Number With Even Digit Frequencies
Learn this problemProblem statement
You are given a string digits containing only the digits 1 and 2.
Delete zero or more characters without changing the relative order of the characters that remain. In the resulting string, both 1 and 2 must occur an even number of times; zero occurrences of a digit is allowed.
Return the numerically largest valid remaining string.
Function
solution(digits: String) → StringExamples
Example 1
digits = "121212"return = "2121"Each digit occurs three times, so one 1 and one 2 must be removed. Removing the first 1 and the last 2 produces 2121, the largest valid result.
Example 2
digits = "2121122"return = "221122"The string has three 1s and four 2s. Removing the first 1 makes both frequencies even and yields 221122.
Example 3
digits = "1111"return = "1111"The four 1s already have even frequency, so keeping every character gives the largest result.
Constraints
3 <= digits.length <= 200000.digitscontains only1and2.