Skip to content
Related Articles

Related Articles

Minimum adjacent swaps of digits required to make N divisible by K

View Discussion
Improve Article
Save Article
  • Last Updated : 28 Jul, 2022

Given two integers N and K, the task is to calculate the minimum number of adjacent swaps of digits required to make the integer N divisible by K

Examples:

Input: N = 12345, K = 2
Output: 1
Explanation: The digits at index 3 and t can be swapped so that the resulting integer is N = 12354, which is divisible by 2. Hence, the required number of adjacent swaps is 1 which is the minimum possible.

Input: N = 10203456, K = 100
Output: 9

Approach: The given problem can be solved by iterating through all the permutations of digits of the given integer and checking for all integers that are divisible by K, the minimum number of adjacent swaps required to convert the given integer to the current integer. Below are the steps to follow:

  • Convert the given integer into a string of characters str, and sort the characters in non-decreasing order.
  • Iterate through all the permutations of str using the inbuilt next_permutation() function.
  • If the integer represented by the current permutation is divisible by K, check for the number of swaps required to convert N into the current integer using this algorithm.
  • Maintain the minimum number of swaps required in a variable which is the required answer.

Below is the implementation of the above approach.

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find minimum number of
// swaps requires to convert s1 to s2
int CountSteps(string s1, string s2, int size)
{
    int i = 0, j = 0;
    int result = 0;
 
    // Iterate over the first string
    // and convert every element
    while (i < size) {
        j = i;
 
        // Find index element of which
        // is equal to the ith element
        while (s1[j] != s2[i]) {
            j += 1;
        }
 
        // Swap adjacent elements in
        // the first string
        while (i < j) {
 
            // Swap elements
            char temp = s1[j];
            s1[j] = s1[j - 1];
            s1[j - 1] = temp;
            j -= 1;
            result += 1;
        }
        i += 1;
    }
    return result;
}
 
// Function to find minimum number of adjacent
// swaps required to make N divisible by K
int swapDigits(int N, int K)
{
    // Convert the integer into string
    string str = to_string(N);
 
    // Sort the elements of the string
    sort(str.begin(), str.end());
 
    // Stores the count of swaps
    int ans = INT_MAX;
 
    // Iterate over all permutations
    // of the given string
    do {
        // If the current integer
        // is divisible by K
        if (stoi(str) % K == 0)
 
            // Update ans
            ans = min(ans,
                      CountSteps(to_string(N), str,
                                 str.length()));
 
    } while (next_permutation(str.begin(),
                              str.end()));
 
    // Return Answer
    return ans;
}
 
// Driver Code
int main()
{
    int N = 10203456;
    int K = 100;
    cout << swapDigits(N, K);
 
    return 0;
}


Java




// Java program for the above approach
 
import java.util.*;
 
public class MapPr {
 
    // Function for next permutation
    static char[] next_permutation(char[] arr)
    {
 
        // Find the length of the array
        int n = arr.length;
 
        // Start from the right most digit and
        // find the first digit that is smaller
        // than the digit next to it.
        int k = n - 2;
        while (k >= 0) {
            if (arr[k] < arr[k + 1])
                break;
 
            k -= 1;
        }
        int l;
        // Reverse the list if the digit that
        // is smaller than the digit next to
        // it is not found.
        if (k < 0)
            Collections.reverse(Arrays.asList(arr));
        else {
            // Find the first greatest element
            // than arr[k] from the end of the list
            for (l = n - 1; l > k; l--) {
                if (arr[l] > arr[k])
                    break;
            }
 
            // Swap the elements at arr[k] and arr[l]
            char temp = arr[l];
            arr[l] = arr[k];
            arr[k] = temp;
        }
        // Reverse the list from k + 1 to the end
        // to find the most nearest greater number
        // to the given input number
 
        int mid = (k + 1) + (arr.length - k - 1) / 2;
        int pos = arr.length - 1;
        for (int i = k + 1; i < mid; i++) {
            char temp = arr[i];
            arr[i] = arr[pos];
            arr[pos--] = temp;
        }
 
        return arr;
    }
 
    // Function to find minimum number of
    // swaps requires to convert s1 to s2
    static int CountSteps(char[] s1, char[] s2, int size)
    {
        int i = 0;
        int j = 0;
        int result = 0;
 
        // Iterate over the first string
        // and convert every element
        while (i < size) {
            j = i;
            // Find index element of which
            // is equal to the ith element
            while (s1[j] != s2[i])
                j += 1;
 
            // Swap adjacent elements in
            // the first string
            while (i < j) {
                // Swap elements
                char temp = s1[j];
                s1[j] = s1[j - 1];
                s1[j - 1] = temp;
                j -= 1;
                result += 1;
            }
            i += 1;
        }
        return result;
    }
 
    // Function to find minimum number of adjacent
    // swaps required to make N divisible by K
    static int swapDigits(int N, int K)
    {
        // Convert the integer into string
        char[] st = (String.valueOf(N)).toCharArray();
        char[] st2 = (String.valueOf(N)).toCharArray();
 
        // Sort the elements of the string
        Arrays.sort(st);
        Arrays.sort(st2);
 
        String st2s = new String(st2);
 
        // Stores the count of swaps
        int ans = Integer.MAX_VALUE;
 
        // Iterate over all permutations
        // of the given string
        // If the current integer
        // is divisible by K
        while (true) {
            st = next_permutation(st);
            String sts = new String(st);
            int sti = Integer.parseInt(sts);
            if (sti % K == 0) {
                ans = Math.min(
                    ans,
                    CountSteps(
                        (String.valueOf(N)).toCharArray(),
                        st, st.length));
            }
            if (sts.equals(st2s))
                break;
        }
 
        // Return Answer
        return ans;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int N = 10203456;
        int K = 100;
        System.out.println(swapDigits(N, K));
    }
}
 
// This code is contributed by phasing17


Python3




# Python 3 program for the above approach
import sys
 
# Function for next permutation
def next_permutation(arr):
 
    # Find the length of the array
    n = len(arr)
 
    # Start from the right most digit and
    # find the first digit that is smaller
    # than the digit next to it.
    k = n - 2
    while k >= 0:
        if arr[k] < arr[k + 1]:
            break
 
        k -= 1
 
    # Reverse the list if the digit that
    # is smaller than the digit next to
    # it is not found.
    if k < 0:
        arr = arr[::-1]
    else:
        # Find the first greatest element
        # than arr[k] from the end of the list
        for l in range(n - 1, k, -1):
            if arr[l] > arr[k]:
                break
 
        # Swap the elements at arr[k] and arr[l
        arr[l], arr[k] = arr[k], arr[l]
 
        # Reverse the list from k + 1 to the end
        # to find the most nearest greater number
        # to the given input number
        arr[k + 1:] = reversed(arr[k + 1:])
 
    return arr
 
# Function to find minimum number of
# swaps requires to convert s1 to s2
def CountSteps(s1,  s2,  size):
 
    i = 0
    j = 0
    result = 0
 
    # Iterate over the first string
    # and convert every element
    while (i < size):
        j = i
        # Find index element of which
        # is equal to the ith element
        while (s1[j] != s2[i]):
            j += 1
 
        # Swap adjacent elements in
        # the first string
        while (i < j):
 
            # Swap elements
            temp = s1[j]
            s1[j] = s1[j - 1]
            s1[j - 1] = temp
            j -= 1
            result += 1
        i += 1
    return result
 
# Function to find minimum number of adjacent
# swaps required to make N divisible by K
def swapDigits(N,  K):
 
    # Convert the integer into string
    st = str(N)
    st2 = str(N)
 
    # Sort the elements of the string
    st = list(st)
    st2 = list(st2)
    st.sort()
    st2.sort()
 
    # Stores the count of swaps
    ans = sys.maxsize
 
    # Iterate over all permutations
    # of the given string
    # If the current integer
    # is divisible by K
    while (next_permutation(st) != st2):
        if(int(''.join(st)) % K == 0):
            ans = min(ans,
                      CountSteps(list(str(N)), st,
                                 len(st)))
 
    # Return Answer
    return ans
   
# Driver Code
if __name__ == "__main__":
 
    N = 10203456
    K = 100
    print(swapDigits(N, K))
 
    # This code is contributed by ukasp.


C#




// C# program for the above approach
using System;
using System.Linq;
using System.Collections.Generic;
 
class GFG {
  // Function for next permutation
  static char[] next_permutation(char[] arr)
  {
 
    // Find the length of the array
    int n = arr.Length;
 
    // Start from the right most digit and
    // find the first digit that is smaller
    // than the digit next to it.
    int k = n - 2;
    while (k >= 0) {
      if (arr[k] < arr[k + 1])
        break;
 
      k -= 1;
    }
    int l;
    // Reverse the list if the digit that
    // is smaller than the digit next to
    // it is not found.
    if (k < 0)
      Array.Reverse(arr);
    else {
      // Find the first greatest element
      // than arr[k] from the end of the list
      for (l = n - 1; l > k; l--) {
        if (arr[l] > arr[k])
          break;
      }
 
      // Swap the elements at arr[k] and arr[l]
      var temp = arr[l];
      arr[l] = arr[k];
      arr[k] = temp;
 
      // Reverse the list from k + 1 to the end
      // to find the most nearest greater number
      // to the given input number
      Array.Reverse(arr, k + 1, arr.Length - k - 1);
    }
    return arr;
  }
 
  // Function to find minimum number of
  // swaps requires to convert s1 to s2
  static int CountSteps(char[] s1, char[] s2, int size)
  {
    int i = 0;
    int j = 0;
    int result = 0;
 
    // Iterate over the first string
    // and convert every element
    while (i < size) {
      j = i;
      // Find index element of which
      // is equal to the ith element
      while (s1[j] != s2[i])
        j += 1;
 
      // Swap adjacent elements in
      // the first string
      while (i < j) {
        // Swap elements
        var temp = s1[j];
        s1[j] = s1[j - 1];
        s1[j - 1] = temp;
        j -= 1;
        result += 1;
      }
      i += 1;
    }
    return result;
  }
 
  // Function to find minimum number of adjacent
  // swaps required to make N divisible by K
  static int swapDigits(int N, int K)
  {
    // Convert the integer into string
    char[] st = (Convert.ToString(N)).ToCharArray();
    char[] st2 = (Convert.ToString(N)).ToCharArray();
 
    // Sort the elements of the string
    Array.Sort(st);
    Array.Sort(st2);
 
    string st2s = new string(st2);
 
    // Stores the count of swaps
    int ans = Int32.MaxValue;
 
    // Iterate over all permutations
    // of the given string
    // If the current integer
    // is divisible by K
    while (true) {
      st = next_permutation(st);
      string sts = new string(st);
      int sti = Convert.ToInt32(sts);
 
      if (sti % K == 0)
        ans = Math.Min(
        ans,
        CountSteps(
          (Convert.ToString(N)).ToCharArray(),
          st, st.Length));
      if (sts == st2s)
        break;
    }
 
    // Return Answer
    return ans;
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
    int N = 10203456;
    int K = 100;
    Console.Write(swapDigits(N, K));
  }
}
 
// This code is contributed by phasing17


Javascript




// JavaScript program for the above approach
 
// Function for next permutation
function next_permutation(arr)
{
 
    // Find the length of the array
    let n = arr.length;
 
    // Start from the right most digit and
    // find the first digit that is smaller
    // than the digit next to it.
    let k = n - 2;
    while (k >= 0)
    {
        if (arr[k] < arr[k + 1])
            break
 
        k -= 1
    }
 
    // Reverse the list if the digit that
    // is smaller than the digit next to
    // it is not found.
    if (k < 0)
        arr.reverse()
    else
    {
        // Find the first greatest element
        // than arr[k] from the end of the list
        for (var l = n - 1; l > k; l -- )
        {
            if (arr[l] > arr[k])
                break
        }
 
        // Swap the elements at arr[k] and arr[l]
        var temp = arr[l]
        arr[l] = arr[k]
        arr[k] = temp
 
        // Reverse the list from k + 1 to the end
        // to find the most nearest greater number
        // to the given input number
        let arr1 = arr.slice(k + 1);
        arr1.reverse();
        for (var i = k + 1; i < arr1.length; i++)
            arr[i] = arr1[i]
    }
    return arr;
}
     
 
// Function to find minimum number of
// swaps requires to convert s1 to s2
function CountSteps(s1,  s2,  size)
{
    let i = 0;
    let j = 0;
    let result = 0;
 
    // Iterate over the first string
    // and convert every element
    while (i < size)
    {
        j = i
        // Find index element of which
        // is equal to the ith element
        while (s1[j] != s2[i])
            j += 1
 
        // Swap adjacent elements in
        // the first string
        while (i < j)
        {
            // Swap elements
            let temp = s1[j]
            s1[j] = s1[j - 1]
            s1[j - 1] = temp
            j -= 1
            result += 1
        }
        i += 1
    }
    return result
}
 
// Function to find minimum number of adjacent
// swaps required to make N divisible by K
function swapDigits(N,  K)
{
    // Convert the integer into string
    st = N.toString()
    st2 = N.toString()
 
    // Sort the elements of the string
    st = st.split("")
    st2 = st2.split("")
    st.sort()
    st2.sort()
 
 
    // Stores the count of swaps
    ans = Number. MAX_VALUE
 
    // Iterate over all permutations
    // of the given string
    // If the current integer
    // is divisible by K
    while (next_permutation(st).join("") != st2.join(""))
    {
        if(parseInt(st.join("")) % K == 0)
            ans = Math.min(ans,  CountSteps((N.toString()).split(""), st, st.length))
        
    }
     
    // Return Answer
    return ans
}
 
// Driver Code
let N = 10203456
let K = 100
console.log(swapDigits(N, K))
 
// This code is contributed by phasing17


 
 

Output

9

 

Time Complexity: O((log N)! * (log N)2)
Auxiliary Space: O(log N)

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!