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
using System ; using System . Collections . Generic ; class GFG { static int moduloEquality ( int [ ] A , int [ ] B , int n , int m ) { Dictionary < int , int > mapA = new Dictionary < int , int > ( ) ; Dictionary < int , int > mapB = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mapA . ContainsKey ( A [ i ] ) ) { mapA [ A [ i ] ] = mapA [ A [ i ] ] + 1 ; } else { mapA . Add ( A [ i ] , 1 ) ; } if ( mapB . ContainsKey ( B [ i ] ) ) { mapB [ B [ i ] ] = mapB [ B [ i ] ] + 1 ; } else { mapB . Add ( B [ i ] , 1 ) ; } } HashSet < int > possibleValues = new HashSet < int > ( ) ; int FirstElement = B [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { int cur = A [ i ] ; possibleValues . Add ( cur > FirstElement ? m - cur + FirstElement : FirstElement - cur ) ; } int ans = Int32 . MaxValue ; foreach ( int it in possibleValues ) { bool possible = true ; foreach ( KeyValuePair < int , int > it2 in mapA ) { if ( it2 . Value != mapB [ ( it2 . Key + it ) % m ] ) { possible = false ; break ; } } if ( possible ) { ans = Math . Min ( ans , it ) ; } } return ans ; } static void Main ( ) { int n = 4 ; int m = 3 ; int [ ] A = { 0 , 0 , 2 , 1 } ; int [ ] B = { 2 , 0 , 1 , 1 } ; Console . WriteLine ( moduloEquality ( A , B , n , m ) ) ; } }