Smallest number to be added in first Array modulo M to make frequencies of both Arrays equal | Java 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
import java . util . * ; class GFG { static int moduloEquality ( int A [ ] , int B [ ] , int n , int m ) { HashMap < Integer , Integer > mapA = new HashMap < Integer , Integer > ( ) ; HashMap < Integer , Integer > mapB = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mapA . containsKey ( A [ i ] ) ) { mapA . put ( A [ i ] , mapA . get ( A [ i ] ) + 1 ) ; } else { mapA . put ( A [ i ] , 1 ) ; } if ( mapB . containsKey ( B [ i ] ) ) { mapB . put ( B [ i ] , mapB . get ( B [ i ] ) + 1 ) ; } else { mapB . put ( B [ i ] , 1 ) ; } } HashSet < Integer > possibleValues = new HashSet < Integer > ( ) ; 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 = Integer . MAX_VALUE ; for ( int it : possibleValues ) { boolean possible = true ; for ( Map . Entry < Integer , Integer > it2 : mapA . entrySet ( ) ) { if ( it2 . getValue ( ) != mapB . get ( ( it2 . getKey ( ) + it ) % m ) ) { possible = false ; break ; } } if ( possible ) { ans = Math . min ( ans , it ) ; } } return ans ; } public static void main ( String [ ] args ) { int n = 4 ; int m = 3 ; int A [ ] = { 0 , 0 , 2 , 1 } ; int B [ ] = { 2 , 0 , 1 , 1 } ; System . out . print ( moduloEquality ( A , B , n , m ) + "NEW_LINE"); } }