Largest Even Number Problem
#3798
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3798.
You are given a string s consisting only of the characters '1' and '2'.
You may delete any number of characters from s without changing the order of the remaining characters.
Return the largest possible resultant string that represents an even integer. If there is no such string, return the empty string "".
Example 1:
Input: s = "1112"
Output: "1112"
Explanation:
The string already represents the largest possible even number, so no deletions are needed.
Example 2:
Input: s = "221"
Output: "22"
Explanation:
Deleting '1' results in the largest possible even number which is equal to 22.
Example 3:
Input: s = "1"
Output: ""
Explanation:
There is no way to get an even number.
Constraints:
1 <= s.length <= 100sconsists only of the characters'1'and'2'.
Solution
Approach: Strip Trailing Ones
The string holds only 1 and 2, so an even number must end in 2. Keeping every character gives the largest value, so we only drop the 1s at the end. If no 2 is left, the answer is the empty string.
Complexity: Time O(n), space O(n) for the result, where n is the length of s.
class Solution:
def largestEven(self, s: str) -> str:
return s.rstrip("1")