MediumNo. 2844
Minimum Operations to Make a Special Number — LeetCode 2844 Python Solution
- Pattern
- Greedy
- Topics
- Greedy, Math, String, Enumeration
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- num = "2245047"
- Output
- 2
- Explanation
- Delete digits num[5] and num[6]. The resulting number is "22450" which is special since it is divisible by 25.
Python solution
class Solution:
def minimumOperations(self, num: str) -> int:
@cache
def dfs(i: int, k: int) -> int:
if i == n:
return 0 if k == 0 else n
ans = dfs(i + 1, k) + 1
ans = min(ans, dfs(i + 1, (k * 10 + int(num[i])) % 25))
return ans
n = len(num)
return dfs(0, 0)Complexity
- Time
- O(n × 25)
- Space · auxiliary
- O(n × 25)
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 2844. Minimum Operations to Make a Special Number is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1247 | Minimum Swaps to Make Strings Equal | Medium |
| 1903 | Largest Odd Number in String | Easy |
| 1927 | Sum Game | Medium |
| 2014 | Longest Subsequence Repeated k Times | Hard |
| 2038 | Remove Colored Pieces if Both Neighbors are the Same Color | Medium |
| 2259 | Remove Digit From Number to Maximize Result | Easy |
Frequently asked questions
- How hard is LeetCode 2844. Minimum Operations to Make a Special Number?
LeetCode 2844. Minimum Operations to Make a Special Number is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2844. Minimum Operations to Make a Special Number?
The Python solution on this page runs in O(n × 25).
- What is the space complexity of LeetCode 2844. Minimum Operations to Make a Special Number?
The Python solution on this page uses O(n × 25) auxiliary space.
- What topics does LeetCode 2844. Minimum Operations to Make a Special Number cover?
LeetCode 2844. Minimum Operations to Make a Special Number is tagged Greedy, Math, String and Enumeration on LeetCode.