Problem Description
You are given a 0-indexed string num
representing a non-negative integer. In one operation, you can pick any digit of num
and delete it. Note that if you delete all the digits of num
, num
becomes 0
. Return the minimum number of operations required to make num
special. An integer x
is considered special if it is divisible by 25
.
Key Insights
- A number is divisible by
25
if it ends in00
,25
,50
, or75
. - The goal is to find the minimum number of deletions needed to form a number that ends with one of these pairs.
- We can iterate through the digits of the number and track the last occurrences of the required pairs.
- The operations needed will be based on how many digits we have to skip or delete to form the special number.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string num
.
Space Complexity: O(1), since we are using a fixed amount of extra space.
Solution
To solve the problem, we can use a greedy approach:
- Start from the end of the string
num
and look for the pairs00
,25
,50
, or75
. - For each pair, count how many digits we need to skip to reach the first digit of the pair and the second digit.
- Keep track of the minimum deletions required for each valid pair found.
- Return the minimum deletions needed to form a special number.