Smallest number to be added in first Array modulo M to make frequencies of both Arrays equal | C ++ program for the above approach ; Utility function to find the answer ; Stores the frequencies of array elements ; Stores the possible values of X ; Generate possible positive values of X ; Initialize answer to MAX value ; Flag to check if the current element of the set can be considered ; If the frequency of an element in A [ ] is not equal to that in B [ ] after the operation ; Current set element cannot be considered ; Update minimum value of X ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int moduloEquality ( int A [ ] , int B [ ] , int n , int m ) { map < int , int > mapA , mapB ; for ( int i = 0 ; i < n ; i ++ ) { mapA [ A [ i ] ] ++ ; mapB [ B [ i ] ] ++ ; } set < int > possibleValues ; int FirstElement = B [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { int cur = A [ i ] ; possibleValues . insert ( cur > FirstElement ? m - cur + FirstElement : FirstElement - cur ) ; } int ans = INT_MAX ; for ( auto it : possibleValues ) { bool possible = true ; for ( auto it2 : mapA ) { if ( it2 . second != mapB [ ( it2 . first + it ) % m ] ) { possible = false ; break ; } } if ( possible ) { ans = min ( ans , it ) ; } } return ans ; } int main ( ) { int n = 4 ; int m = 3 ; int A [ ] = { 0 , 0 , 2 , 1 } ; int B [ ] = { 2 , 0 , 1 , 1 } ; cout << moduloEquality ( A , B , n , m ) << endl ; return 0 ; }