#2844
Minimum Operations to Make a Special Number
MediumMathStringGreedyEnumerationGreedyEnumeration
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution focuses on finding the last two digits that can form a special number directly by scanning the string from the end. This avoids unnecessary checks and directly counts the deletions needed.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a variable to count deletions and set it to 0.
- 2Step 2: Traverse the string from the end to the beginning, looking for pairs of digits that can form '00', '25', '50', or '75'.
- 3Step 3: For each valid pair found, calculate the number of deletions needed and update the minimum operations.
solution.py17 lines
1# Full working Python code
2
3def min_operations_optimal(num):
4 n = len(num)
5 min_ops = float('inf')
6 for i in range(n - 1, -1, -1):
7 if num[i] == '0':
8 for j in range(i - 1, -1, -1):
9 if num[j] == '0':
10 min_ops = min(min_ops, (i - j - 1))
11 elif num[j] == '5':
12 min_ops = min(min_ops, (i - j - 1) + 1)
13 elif num[j] == '2':
14 min_ops = min(min_ops, (i - j - 1) + 2)
15 elif num[j] == '7':
16 min_ops = min(min_ops, (i - j - 1) + 2)
17 return min_ops if min_ops != float('inf') else nℹ
Complexity note: The time complexity is O(n) because we only traverse the string once, checking pairs of digits in a single pass. This is efficient compared to the brute force method.
- 1A number is special if it ends with '00', '25', '50', or '75'.
- 2The optimal solution leverages the structure of the problem by focusing on the last two digits.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.