Smallest number to be added in first Array modulo M to make frequencies of both Arrays equal | 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
function moduloEquality ( A , B , n , m ) { var mapA = new Map ( ) , mapB = new Map ( ) ; for ( var i = 0 ; i < n ; i ++ ) { if ( mapA . has ( A [ i ] ) ) mapA . set ( A [ i ] , mapA . get ( A [ i ] ) + 1 ) else mapA . set ( A [ i ] , 1 ) if ( mapB . has ( B [ i ] ) ) mapB . set ( B [ i ] , mapB . get ( B [ i ] ) + 1 ) else mapB . set ( B [ i ] , 1 ) } var possibleValues = new Set ( ) ; var FirstElement = B [ 0 ] ; for ( var i = 0 ; i < n ; i ++ ) { var cur = A [ i ] ; possibleValues . add ( cur > FirstElement ? m - cur + FirstElement : FirstElement - cur ) ; } var ans = 1000000000 ; possibleValues . forEach ( it => { var possible = true ; mapA . forEach ( ( value , key ) => { if ( value != mapB . get ( ( key + it ) % m ) ) { possible = false ; } } ) ; if ( possible ) { ans = Math . min ( ans , it ) ; } } ) ; return ans ; } var n = 4 ; var m = 3 ; var A = [ 0 , 0 , 2 , 1 ] ; var B = [ 2 , 0 , 1 , 1 ] ; document . write ( moduloEquality ( A , B , n , m ) ) ;