Leetcode 2844: Minimum Operations to Make a Special Number

grid47
grid47
Exploring patterns and algorithms
Jan 27, 2024 6 min read

You are given a non-negative integer represented as a string num. In one operation, you can remove any single digit from the string. If you remove all digits, the result becomes 0. Your task is to return the minimum number of operations required to make the number divisible by 25. A number is divisible by 25 if it ends in 00, 25, 50, or 75.
Problem
Approach
Steps
Complexity
Input: The input is a string num representing a non-negative integer.
Example: num = "78492"
Constraints:
• 1 <= num.length <= 100
• num only consists of digits '0' through '9'.
• num does not contain any leading zeros.
Output: Return the minimum number of operations required to make num divisible by 25.
Example: 2
Constraints:
• The output should be a single integer representing the minimum number of operations.
Goal: To find the minimum number of operations to make the number divisible by 25.
Steps:
• Loop through the digits of the number from the end (rightmost side).
• Check if the current digits can form a valid pair (00, 25, 50, or 75).
• Track if '0' and '5' are found to make possible combinations.
• Count and remove digits to form a number ending in one of the valid pairs.
Goal: The input string follows these constraints:
Steps:
• 1 <= num.length <= 100
• The string contains only digits '0' to '9'.
• No leading zeros are allowed in the input.
Assumptions:
• The string will always represent a valid non-negative integer.
Input: num = "78492"
Explanation: The number 78492 is not divisible by 25. To make it divisible by 25, delete digits 4 and 9 to get 780, which ends in 00, making it divisible by 25.

Input: num = "12000"
Explanation: The number 12000 is divisible by 25 if the last two digits are kept. Delete digits 2 and 3 to get 1200, which ends in 00, making it divisible by 25.

Input: num = "4510"
Explanation: The number 4510 can be made divisible by 25 by removing digit 1. The resulting number 450 ends in 50, making it divisible by 25.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus