Given two N-digit positive integers X and Y, the task is to find the minimum absolute difference between both the integers possible by rearranging the digits of both the integers in the same order.
Input: X = 5181, Y = 3663
Rearranging the digits of both the given integers in the order of (3, 2, 4, 1) modifies the value of X and Y as 8115 and 6633 respectively.
Therefore, the absolute difference between the two is (8115 – 6633) = 1482, which is the minimum possible difference.
Input: X = 37198, Y = 44911
Approach: The given problem can be solved by finding the absolute difference between every permutation of X and Y having the same order of rearrangements of digits. Follow the steps below to solve the problem:
- Initialize a 2D array arr[N], that stores the digits of numbers X and Y respectively.
- Initialize an array, say P, that stores the permutation of the numbers [0, N – 1].
- Initialize a variable, say minDIff that stores the minimized difference between X and Y.
- Traverse the all possible permutation of P and perform the following steps:
- Rearrange the digits of X and Y according to the permutation and store the absolute difference between them in a variable say difference.
- After the above steps, update the value of minDIff as the minimum of minDiff and difference.
- After completing the above steps, print the value of minDIff as the minimum difference.
Below is the implementation of the above approach:
Time Complexity: O(N!)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.