Minimum Operations to Make a Special Number — LeetCode 2844 Python Solution
MediumGreedyMathStringEnumeration
- Problem
- #2844
- Pattern
- Greedy
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n \times 25) |
| Space | O(n \times 25) auxiliary |
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
LeetCode 1247Minimum Swaps to Make Strings EqualMediumLeetCode 1903Largest Odd Number in StringEasyLeetCode 1927Sum GameMediumLeetCode 2014Longest Subsequence Repeated k TimesHardLeetCode 2038Remove Colored Pieces if Both Neighbors are the Same ColorMediumLeetCode 2259Remove Digit From Number to Maximize ResultEasy
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 \times 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 \times 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.