Problem Description
Given a non-negative integer in the form of a string, you are allowed to delete any digit (each deletion counts as one operation). Your goal is to perform the minimum number of deletions so that the resulting number (which can be interpreted as 0 if all digits are removed) is a special number, where a special number is one that is divisible by 25 (i.e. its last two digits are one of "00", "25", "50", or "75").
Key Insights
- A number is divisible by 25 if and only if its last two digits are any of "00", "25", "50", or "75".
- Work from the right side of the string to find the required pair of digits while preserving their relative order.
- For each potential ending pair, count the number of deletions needed: deletions after the last digit candidate and deletions between the two digit candidates.
- Iterate through all four candidate pairs to find the minimum deletion count needed.
Space and Time Complexity
Time Complexity: O(n) per candidate, and since there are 4 fixed candidates, overall time is O(n).
Space Complexity: O(1) extra space.
Solution
We solve the problem by checking all possible valid endings ("00", "25", "50", "75"). For each candidate ending:
- Traverse the input string from right to left to find the digit that should be at the unit place.
- Continue the reverse traversal to find the digit that should be at the tens place (it must appear before the unit digit).
- Calculate deletions needed:
- The number of digits after the chosen unit digit.
- The number of digits between the chosen tens and unit digits that are not part of the final special number.
- The answer is the minimum deletion count over all candidates. If a candidate ending cannot be formed, it is skipped.