Minimum Operations to Make a Special Number - Problem

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.

Input & Output

Example 1 — Basic Pattern
$ Input: num = "2245047"
Output: 2
💡 Note: We can form "2250" by deleting the digits '4' and '7'. Since 2250 % 25 = 0, we need 2 operations.
Example 2 — Single Zero
$ Input: num = "2908305"
Output: 3
💡 Note: We can form "2900" by deleting '8', '3', '5'. Since 2900 % 25 = 0, we need 3 operations.
Example 3 — Already Special
$ Input: num = "10"
Output: 1
💡 Note: 10 is not divisible by 25. We delete '1' to get '0', and 0 % 25 = 0, so we need 1 operation.

Constraints

  • 1 ≤ num.length ≤ 105
  • num consists of only digits
  • num does not contain any leading zeros

Visualization

Tap to expand
Minimum Operations to Make a Special Number INPUT String num: 2 0 2 1 4 2 5 3 0 4 4 5 7 6 Divisible by 25 endings: 00 25 50 75 Goal: Find minimum deletions to end in 00, 25, 50, or 75 Input: num = "2245047" ALGORITHM STEPS 1 Scan from right Find last digit: 0 or 5 2 Found '7' at idx 6 Skip, not 0 or 5 3 Check patterns Try ending with 50 Pattern Search: 2 2 4 5 0 4 7 Find '5' before '0' --> "50" pattern! 4 Count deletions Delete '4' and '7' = 2 ops 224504 7 --> 22450 2245 0 4 --> 224550 FINAL RESULT Original string: 2 2 4 5 0 4 7 Keep Delete Resulting number: 2 2 4 5 0 22450 / 25 = 898 [OK] Divisible by 25! Output: 2 Key Insight: A number is divisible by 25 if it ends in 00, 25, 50, or 75. Use greedy approach: scan from right to find valid two-digit endings. For each pattern, count digits to delete between and after the pair. Return minimum deletions across all valid patterns. Time: O(n), Space: O(1). TutorialsPoint - Minimum Operations to Make a Special Number | Greedy Pattern Matching
Asked in
Google 23 Amazon 18 Microsoft 15
28.5K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen