Minimum value by which each Array element must be added as per given conditions

Given 2 arrays A[] and B[] and an integer M. The task is to find the minimum value of X such that after changing all the elements of the array to (arr[i] + X)%M frequency of all the elements of A[] is same as the frequency of all the elements of B[]. Print “-1” if it is not possible to find any value of X.
Examples: 

Input: M = 3, A[] = {0, 0, 2, 1}, B[] = {2, 0, 1, 1} 
Output:
Explanation: 
On taking x = 1 the numbers are changed to: 
(0 + 1) % 3 = 1 
(0 + 1) % 3 = 1 
(2 + 1) % 3 = 0 
(1 + 1) % 3 = 2 
Hence on rearranging 1, 1, 0, 2 to 2, 0, 1, 1, array B[] is obtained.
Input: M = 887, A[] = {4625, 5469, 2038, 5916}, B[] = {744, 211, 795, 695} 
Output: -1 
Explanation: 
The conversion of A[] to B[] is not possible. 

Approach: The possible value of X will be in the range [0, M] as the value after the range M will give the same result we are performing modulo to M. Below are the steps:  

  1. Create the frequency array(say freqB[]) of the array B[].
  2. Now, iterate for all possible value of X in the range [0, M] and do the following: 
    • For each value of X in the above range update the array A[] to (arr[i] + X)%M.
    • Create the frequency array(say freqA[]) of the array A[].
    • If the frequency of the array freqA[] and freqB[] is the same then print this value of X.
    • Else check for another value of X.
  3. After the above step if we don’t find the value of X then print “-1”.

Below is the implementation of the above approach:
 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find minimum value of X
int findX(int n, int m,
          int ar1[], int ar2[])
{
    // Create a frequency array for B[]
    int freq2[m] = { 0 };
  
    for (int i = 0; i < n; i++) {
        freq2[ar2[i]]++;
    }
  
    // Intialize x = -1
    int x = -1;
  
    // Loop from [0 to m-1]
    for (int i = 0; i < m; i++) {
  
        int cnt = 0;
        int freq1[m] = { 0 };
  
        // Create a frequency array
        // for fixed x for all ar[i]
        for (int j = 0; j < n; j++) {
  
            freq1[(ar1[j] + i) % m]++;
        }
  
        bool flag = true;
  
        // Comparing freq1[] and freq2[]
        for (int k = 0; k < m; k++) {
  
            if (freq1[k] != freq2[k]) {
                flag = false;
                break;
            }
        }
  
        // If condition is satisfied
        // then break out from loop
        if (flag) {
            x = i;
            break;
        }
    }
  
    // Return the answer
    return x;
}
  
// Driver Code
int main()
{
    // Given value of M
    int M = 3;
  
    // Given arrays ar1[] and ar2[]
    int ar1[] = { 0, 0, 2, 1 };
    int ar2[] = { 2, 0, 1, 1 };
  
    int N = sizeof arr1 / sizeof arr1[0];
  
    cout << findX(N, M, ar1, ar2) << '\n';
  
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for 
# the above approach
  
# Function to find 
# minimum value of X
def findX(n, m, 
          ar1, ar2):
  
    # Create a frequency 
    # array for B[]
    freq2 = [0] * m
  
    for i in range(n):
        freq2[ar2[i]] += 1
    
    # Intialize x = -1
    x = -1
  
    # Loop from [0 to m - 1]
    for i in range(m):
        cnt = 0
        freq1 = [0] * m
  
        # Create a frequency array
        # for fixed x for all ar[i]
        for j in range(n):
            freq1[(ar1[j] + i) % m] += 1
         
        flag = True
  
        # Comparing freq1[] 
        # and freq2[]
        for k in range(m):
            if (freq1[k] != freq2[k]):
                flag = False
                break
       
        # If condition is satisfied
        # then break out from loop
        if (flag):
            x = i
            break
  
    # Return the answer
    return x
  
# Driver Code
if __name__ == "__main__":
    
    # Given value of M
    M = 3
  
    # Given arrays ar1[] 
    # and ar2[]
    ar1 = [0, 0, 2, 1]
    ar2 = [2, 0, 1, 1]
  
    N = len(ar1)
    print (findX(N, M, ar1, ar2))
      
# This code is contributed by Chitranayal

chevron_right


Output: 

1

 

Time Complexity: O(N*M), where N is the number of elements in the array and M is an integer. 
Auxiliary Space: 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 Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : chitranayal

Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.