Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2844. Minimum Operations to Make a Special Number

Explanation

To solve this problem, we can iterate through the given number and consider all possible positions to split the number into two parts. We then calculate the number of operations required to make each part divisible by 25. The minimum number of operations needed to make the entire number divisible by 25 is the sum of operations required for the two parts.

Algorithm:

  1. Iterate through the given number and consider all possible split positions.
  2. Calculate the number of operations required to make each part divisible by 25.
  3. Keep track of the minimum number of operations found so far.

Time Complexity: O(n^2) where n is the length of the input number. Space Complexity: O(1)

class Solution {
    public int minOperations(String num) {
        int n = num.length();
        int minOps = Integer.MAX_VALUE;
        
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int ops = 0;
                String part1 = num.substring(0, i) + num.substring(j);
                String part2 = num.substring(i, j);
                
                ops += countOps(part1);
                ops += countOps(part2);
                
                minOps = Math.min(minOps, ops);
            }
        }
        
        return minOps;
    }
    
    private int countOps(String part) {
        int n = part.length();
        int ops1 = helper(part, "00");
        int ops2 = helper(part, "25");
        int ops3 = helper(part, "50");
        int ops4 = helper(part, "75");
        
        return Math.min(ops1, Math.min(ops2, Math.min(ops3, ops4)));
    }
    
    private int helper(String part, String target) {
        int i = part.length() - 1;
        int j = target.length() - 1;
        int ops = 0;
        
        while (i >= 0 && j >= 0) {
            if (part.charAt(i) == target.charAt(j)) {
                i--;
                j--;
            } else {
                ops++;
                i--;
            }
        }
        
        ops += j + 1;
        return ops;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.