Smallest number to be added in first Array modulo M to make frequencies of both Arrays equal | Python3 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 sys NEW_LINE from collections import defaultdict NEW_LINE def moduloEquality ( A , B , n , m ) : NEW_LINE INDENT mapA = defaultdict ( int ) NEW_LINE mapB = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mapA [ A [ i ] ] += 1 NEW_LINE mapB [ B [ i ] ] += 1 NEW_LINE DEDENT possibleValues = set ( ) NEW_LINE FirstElement = B [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT cur = A [ i ] NEW_LINE if cur > FirstElement : NEW_LINE INDENT possibleValues . add ( m - cur + FirstElement ) NEW_LINE DEDENT else : NEW_LINE INDENT possibleValues . add ( FirstElement - cur ) NEW_LINE DEDENT DEDENT ans = sys . maxsize NEW_LINE for it in possibleValues : NEW_LINE INDENT possible = True NEW_LINE for it2 in mapA : NEW_LINE INDENT if ( mapA [ it2 ] != mapB [ ( it2 + it ) % m ] ) : NEW_LINE INDENT possible = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( possible ) : NEW_LINE INDENT ans = min ( ans , it ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE m = 3 NEW_LINE A = [ 0 , 0 , 2 , 1 ] NEW_LINE B = [ 2 , 0 , 1 , 1 ] NEW_LINE print ( moduloEquality ( A , B , n , m ) ) NEW_LINE DEDENT