Minimum Operations to Make a Special Number — LeetCode 2844 Python Solution

MediumGreedyMathStringEnumeration
Problem
#2844
Pattern
Greedy
Reading time
2 min

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

MeasureComplexity
TimeO(n \times 25)
SpaceO(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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview