Count ways to generate an array having distinct elements at M consecutive indices | Java program for the above approach ; 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
import java . io . * ; class GFG { static int Fact ( int N ) { int result = 1 ; for ( int i = 1 ; i <= N ; i ++ ) { result = ( result * i ) ; } return result ; } static void numberOfWays ( int M , int [ ] arr , int N ) { int [ ] B = new int [ M ] ; int [ ] counter = new int [ M + 1 ] ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] != 0 ) { if ( B [ i % M ] == 0 ) { B [ i % M ] = arr [ i ] ; counter [ arr [ i ] ] ++ ; if ( counter [ arr [ i ] ] > 1 ) { System . out . println ( 0 ) ; return ; } } else if ( B [ i % M ] != arr [ i ] ) { System . out . println ( 0 ) ; return ; } } } int cnt = 0 ; for ( int i = 0 ; i < M ; i ++ ) { if ( B [ i ] == 0 ) { cnt ++ ; } } System . out . println ( Fact ( cnt ) ) ; } public static void main ( String [ ] args ) { int M = 4 ; int [ ] arr = new int [ ] { 1 , 0 , 3 , 0 , 0 } ; int N = arr . length ; numberOfWays ( M , arr , N ) ; } }