Minimum Operations to Make a Special Number - Problem
You're given a string num representing a non-negative integer. Your task is to make this number special by deleting as few digits as possible.
A number is considered special if it's divisible by 25. This means the number must end in one of these patterns: 00, 25, 50, or 75.
Operations allowed:
- Delete any digit from the string
- If all digits are deleted, the number becomes
0(which is divisible by 25)
Goal: Return the minimum number of deletions needed to make the number divisible by 25.
Example: For num = "2245047", you can delete "2245047" โ "2250" (delete '4' and '7') to get a number ending in '50', which requires 2 operations.
Input & Output
example_1.py โ Basic Pattern Matching
$
Input:
num = "2245047"
โบ
Output:
2
๐ก Note:
We can delete digits to form "2250" (ending in 50, divisible by 25). Delete positions with '4' and '7', requiring 2 operations.
example_2.py โ Multiple Valid Patterns
$
Input:
num = "2908305"
โบ
Output:
3
๐ก Note:
Multiple patterns possible: keep "00" (4 deletions), keep "25" (5 deletions), keep "50" (5 deletions), or make "0" (6 deletions). Best is keeping "00" with 4 deletions... wait, let me recalculate: we can make "2250" by deleting '9','8','3' (3 deletions).
example_3.py โ Edge Case: Single Zero
$
Input:
num = "0"
โบ
Output:
0
๐ก Note:
The number is already 0, which is divisible by 25. No operations needed.
Constraints
- 1 โค num.length โค 105
- num consists of only digits
- num does not contain any leading zeros except for the number 0 itself
Visualization
Tap to expand
Understanding the Visualization
1
Identify Target
Numbers divisible by 25 must end in: 00, 25, 50, or 75
2
Work Backwards
Scan from right to find each pattern with minimum deletions
3
Special Case
Consider making the number 0 by keeping just one zero
4
Choose Minimum
Return the pattern requiring the fewest deletions
Key Takeaway
๐ฏ Key Insight: Since divisibility by 25 requires specific ending patterns, we can work backwards greedily to find the optimal pattern with minimum deletions in linear time.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code