Count ways to generate an array having distinct elements at M consecutive indices | Modular function to calculate factorial ; Stores factorial of N ; Iterate over the range [ 1 , N ] ; Update result ; Function to count ways to replace array elements having 0 s with non - zero elements such that any M consecutive elements are distinct ; Store m consecutive distinct elements such that arr [ i ] is equal to B [ i % M ] ; Stores frequency of array elements ; Traverse the array arr ; If arr [ i ] is non - zero ; If B [ i % M ] is equal to 0 ; Update B [ i % M ] ; Update frequency of arr [ i ] ; If a duplicate element found in M consecutive elements ; Handling the case of inequality ; Stores count of 0 s in B ; Traverse the array , B ; If B [ i ] is 0 ; Update cnt ; Calculate factorial ; Driver Code ; Given M ; Given array ; Size of the array ; Function Call
def Fact ( N ) : NEW_LINE INDENT result = 1 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT result = ( result * i ) NEW_LINE DEDENT return result NEW_LINE DEDENT def numberOfWays ( M , arr , N ) : NEW_LINE INDENT B = [ 0 ] * ( M ) NEW_LINE counter = [ 0 ] * ( M + 1 ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( arr [ i ] != 0 ) : NEW_LINE INDENT if ( B [ i % M ] == 0 ) : NEW_LINE INDENT B [ i % M ] = arr [ i ] NEW_LINE counter [ arr [ i ] ] += 1 NEW_LINE if ( counter [ arr [ i ] ] > 1 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT DEDENT elif ( B [ i % M ] != arr [ i ] ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT cnt = 0 NEW_LINE for i in range ( 0 , M ) : NEW_LINE INDENT if ( B [ i ] == 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT print ( Fact ( cnt ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT M = 4 NEW_LINE arr = [ 1 , 0 , 3 , 0 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE numberOfWays ( M , arr , N ) NEW_LINE DEDENT