Minimum adjacent swaps of digits required to make N divisible by K
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
Time Complexity: O((log N)! * (log N)2)
Auxiliary Space: O(log N)
Similar Reads
Find N numbers such that a number and its reverse are divisible by sum of its digits Given a number N, the task is to print the first N numbers such that every number and the reverse of the number is divisible by its sum of digits.Example: Input: N = 4 Output: 1 2 3 4 Explanation: The reverse of every single digit number is the same number. And, every number is divisible by itself.
9 min read
Sum of last digit of all integers from 1 to N divisible by M Given two integer N and N. The task is to compute the sum of last digit of all integers from 1 to N that is divisible by M. Examples: Input: N = 12, M = 1 Output: 48 Number divisible by M = 1 from 1 to 12 is : {1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 0 + 1 + 2} = 48 Input: N = 100, M = 3 Output: 153 App
6 min read
C++ Program for Smallest K digit number divisible by X Integers X and K are given. The task is to find the smallest K-digit number divisible by X. Examples: Input : X = 83, K = 5 Output : 10043 10040 is the smallest 5 digit number that is multiple of 83. Input : X = 5, K = 2 Output : 10 An efficient solution would be : Compute MIN : smallest K-digit num
2 min read
C++ Program to Rotate digits of a given number by K Given two integers N and K, the task is to rotate the digits of N by K. If K is a positive integer, left rotate its digits. Otherwise, right rotate its digits. Examples: Input: N = 12345, K = 2Output: 34512 Explanation: Left rotating N(= 12345) by K(= 2) modifies N to 34512. Therefore, the required
2 min read
Minimum N-Digit number required to obtain largest N-digit number after performing given operations Given a positive integer N, the task is to find the minimum N-digit number such that performing the following operations on it in the following order results into the largest N-digit number: Convert the number to its Binary Coded Decimal form.Concatenate all the resulting nibbles to form a binary nu
5 min read
Generate all possible permutations of a Number divisible by N Given a numerical string S, the task is to print all the permutations of the string which are divisible by N. Examples: Input: N = 5, S = "125" Output: 125 215Explanation: All possible permutations are S are {125, 152, 215, 251, 521, 512}. Out of these 6 permutations, only 2 {125, 215} are divisible
5 min read