Skip to content
Related Articles

Related Articles

Minimum number of swaps required to make a number divisible by 60
  • Last Updated : 21 Apr, 2020
GeeksforGeeks - Summer Carnival Banner

Given an integer N , the task is to find the minimum number of swaps required to make N divisible by 60. If not possible, then print “-1“.

Examples:

Input: N = 603
Output: 2
Explanation:
Two swap operations are required:
In the first swap (0, 3): 630
In the second swap (6, 3): 360
Now 360 is divisible by 60.
Therefore the minimum two swaps are required.

Input: N = 205
Output: -1

Approach:



  1. For a number to be divisible by 60, it must be divisible by 2, 3 and 10. Therefore:
    • If the sum of digits of number is not divisible by 3, or
    • If there is no digits which is divisible by 2, or
    • If the number does not contain any 0,

    No swap can make the number divisible by 60. Hence -1 swaps will be required in this case.

  2. Then the minimum number of swaps required can be determined by following rules:
    • If the number is already is divisible by 60, then 0 swaps are required. This can be determined if last digit (LSB) is 0 and the second last digit is divisible by 2.
    • If either of the below cases is true, then 1 swap is required.
      • If last digit (LSB) is 0 and the second last digit is not divisible by 2, or, last digit (LSB) is divisible by 2 and the second last digit is 0.
      • If last digit (LSB) is 0 and the second last digit is not divisible by 2, and there are more than 1 zeroes present in the number.
    • Otherwise 2 swaps required

Below is the implementation of the above approach

CPP




// C++ program to find minimum number
// of swap operations required
#include <bits/stdc++.h>
using namespace std;
  
// Function that print minimum number
// of swap operations required
void MinimumSwapOperations(string s)
{
    bool zero_exist = false;
    bool multiple_of_2 = false;
    int sum = 0;
    int index_of_zero;
    bool more_zero = false;
  
    for (int i = 0; i < s.length(); i++) {
        int val = s[i] - '0';
  
        // Condition if more than one
        // zero exist
        if (zero_exist == true)
            more_zero = true;
  
        // Condition if zero_exist
        if (val == 0) {
            zero_exist = true;
            index_of_zero = i;
        }
  
        // Computing total sum of all digits
        sum += val;
    }
  
    // Condition if zero does not exist or
    // the sum is not divisible by 3
    if (zero_exist == false || sum % 3 != 0) {
        cout << "-1"
             << "\n";
        return;
    }
  
    for (int i = 0; i < s.length(); i++) {
        int val = s[i] - '0';
  
        // Condition to find a digit that is
        // multiple of 2 other than one zero
        if (val % 2 == 0 && i != index_of_zero)
            multiple_of_2 = true;
    }
  
    // Condition if multiple of 2
    // do not exist
    if (multiple_of_2 == false) {
        cout << "-1"
             << "\n";
        return;
    }
  
    int last_val = s[s.length() - 1] - '0';
    int second_last_val = s[s.length() - 2]
                          - '0';
  
    // Condition for zero swaps
    // means the number is already
    // is divisible by 60
    if (last_val == 0
        && second_last_val % 2 == 0)
        cout << 0 << "\n";
  
    // Condition for only one swap
    else if ((last_val == 0
              && second_last_val % 2 != 0)
             || (last_val % 2 == 0
                 && second_last_val == 0))
        cout << 1 << "\n";
  
    else if (more_zero == true
             && (last_val == 0
                 && second_last_val % 2 != 0))
        cout << 1 << "\n";
  
    // Otherwise 2 swaps required
    else
        cout << 2 << "\n";
}
  
// Driver Code
int main()
{
    string N = "20";
  
    MinimumSwapOperations(N);
  
    return 0;
}

Java




// Java program to find minimum number
// of swap operations required
class GFG {
      
    // Function that print minimum number
    // of swap operations required
    static void MinimumSwapOperations(String s)
    {
        boolean zero_exist = false;
        boolean multiple_of_2 = false;
        int sum = 0;
        int index_of_zero = 0;
        boolean more_zero = false;
      
        for (int i = 0; i < s.length(); i++) {
            int val = s.charAt(i) - '0';
      
            // Condition if more than one
            // zero exist
            if (zero_exist == true)
                more_zero = true;
      
            // Condition if zero_exist
            if (val == 0) {
                zero_exist = true;
                index_of_zero = i;
            }
      
            // Computing total sum of all digits
            sum += val;
        }
      
        // Condition if zero does not exist or
        // the sum is not divisible by 3
        if (zero_exist == false || sum % 3 != 0) {
            System.out.println("-1");
            return;
        }
      
        for (int i = 0; i < s.length(); i++) {
            int val = s.charAt(i) - '0';
      
            // Condition to find a digit that is
            // multiple of 2 other than one zero
            if (val % 2 == 0 && i != index_of_zero)
                multiple_of_2 = true;
        }
      
        // Condition if multiple of 2
        // do not exist
        if (multiple_of_2 == false) {
            System.out.println("-1");
            return;
        }
      
        int last_val = s.charAt(s.length() - 1)- '0';
        int second_last_val = s.charAt(s.length() - 2)- '0';
      
        // Condition for zero swaps
        // means the number is already
        // is divisible by 60
        if (last_val == 0&& second_last_val % 2 == 0)
            System.out.println(0);
      
        // Condition for only one swap
        else if ((last_val == 0
                  && second_last_val % 2 != 0)
                 || (last_val % 2 == 0
                     && second_last_val == 0))
            System.out.println(1);
      
        else if (more_zero == true
                 && (last_val == 0
                     && second_last_val % 2 != 0))
            System.out.println(1) ;
      
        // Otherwise 2 swaps required
        else
            System.out.println(2) ;
    }
      
    // Driver Code
    public static void main (String[] args)
    {
        String N = "20";
      
        MinimumSwapOperations(N);
      
    }
}
  
// This code is contributed by AnkitRai01

Python3




# Python3 program to find minimum number
# of swap operations required
  
# Function that prminimum number
# of swap operations required
def MinimumSwapOperations(s):
    zero_exist = False
    multiple_of_2 = False
    sum = 0
    index_of_zero = 0
    more_zero = False
  
    for i in range(len(s)):
        val = ord(s[i]) - ord('0')
  
        # Condition if more than one
        # zero exist
        if (zero_exist == True):
            more_zero = True
  
        # Condition if zero_exist
        if (val == 0):
            zero_exist = True
            index_of_zero = i
  
        # Computing total sum of all digits
        sum += val
  
    # Condition if zero does not exist or
    # the sum is not divisible by 3
    if (zero_exist == False or sum % 3 != 0):
        print("-1")
        return
  
    for i in range(len(s)):
        val = ord(s[i]) - ord('0')
  
        # Condition to find a digit that is
        # multiple of 2 other than one zero
        if (val % 2 == 0 and i != index_of_zero):
            multiple_of_2 = True
  
    # Condition if multiple of 2
    # do not exist
    if (multiple_of_2 == False):
        print("-1")
        return
  
    last_val = ord(s[len(s) - 1]) - ord('0')
    second_last_val = ord(s[len(s) - 2])- ord('0')
  
    # Condition for zero swaps
    # means the number is already
    # is divisible by 60
    if (last_val == 0
        and second_last_val % 2 == 0):
        print(0)
  
    # Condition for only one swap
    elif ((last_val == 0
            and second_last_val % 2 != 0)
            or (last_val % 2 == 0
                and second_last_val == 0)):
        print(1)
  
    elif (more_zero == True
            and (last_val == 0
                and second_last_val % 2 != 0)):
        print(1)
  
    # Otherwise 2 swaps required
    else:
        print(2)
  
# Driver Code
if __name__ == '__main__':
    N = "20"
  
    MinimumSwapOperations(N)
  
# This code is contributed by mohit kumar 29

C#




// C# program to find minimum number
// of swap operations required
using System;
  
class GFG {
      
    // Function that print minimum number
    // of swap operations required
    static void MinimumSwapOperations(string s)
    {
        bool zero_exist = false;
        bool multiple_of_2 = false;
        int sum = 0;
        int index_of_zero = 0;
        bool more_zero = false;
      
        for (int i = 0; i < s.Length; i++) {
            int val = s[i] - '0';
      
            // Condition if more than one
            // zero exist
            if (zero_exist == true)
                more_zero = true;
      
            // Condition if zero_exist
            if (val == 0) {
                zero_exist = true;
                index_of_zero = i;
            }
      
            // Computing total sum of all digits
            sum += val;
        }
      
        // Condition if zero does not exist or
        // the sum is not divisible by 3
        if (zero_exist == false || sum % 3 != 0) {
            Console.WriteLine("-1");
            return;
        }
      
        for (int i = 0; i < s.Length; i++) {
            int val = s[i] - '0';
      
            // Condition to find a digit that is
            // multiple of 2 other than one zero
            if (val % 2 == 0 && i != index_of_zero)
                multiple_of_2 = true;
        }
      
        // Condition if multiple of 2
        // do not exist
        if (multiple_of_2 == false) {
            Console.WriteLine("-1");
            return;
        }
      
        int last_val = s[(s.Length - 1)- '0'];
        int second_last_val = s[(s.Length - 2)- '0'];
      
        // Condition for zero swaps
        // means the number is already
        // is divisible by 60
        if (last_val == 0&& second_last_val % 2 == 0)
           Console.WriteLine(0);
      
        // Condition for only one swap
        else if ((last_val == 0
                  && second_last_val % 2 != 0)
                 || (last_val % 2 == 0
                     && second_last_val == 0))
           Console.WriteLine(1);
      
        else if (more_zero == true
                 && (last_val == 0
                     && second_last_val % 2 != 0))
            Console.WriteLine(1) ;
      
        // Otherwise 2 swaps required
        else
            Console.WriteLine(2) ;
    }
      
    // Driver Code
    public static void Main (string[] args)
    {
        string N = "20";
      
        MinimumSwapOperations(N);
      
    }
}
  
// This code is contributed by AnkitRai01
Output:
-1

Time complexity: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :