Given N students and a total of M sets of question paper where M ? N. All the M sets are different and every sets is available in sufficient quantity. All the students are sitting in a single row. The task is to find the number of ways to distribute the question paper so that if any M consecutive students are selected then each student has a unique question paper set. The answer could be large, so print the answer modulo 109 + 7.
Example:
Input: N = 2, M = 2
Output: 2
(A, B) and (B, A) are the only possible ways.
Input: N = 15, M = 4
Output: 24
Approach: It can be observed that the number of ways are independent of N and only depend on M. First M students can be given M sets and then the same pattern can be repeated. The number of ways to distribute the question paper in this way is M!. For example,
N = 6, M = 3
A, B, C, A, B, C
A, C, B, A, C, B
B, C, A, B, C, A
B, A, C, B, A, C
C, A, B, C, A, B
C, B, A, C, B, A
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
int factMod( int n)
{
long fact = 1;
for ( int i = 2; i <= n; i++) {
fact *= (i % MOD);
fact %= MOD;
}
return fact;
}
int countWays( int n, int m)
{
return factMod(m);
}
int main()
{
int n = 2, m = 2;
cout << countWays(n, m);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int MOD = 1000000007 ;
static int factMod( int n)
{
long fact = 1 ;
for ( int i = 2 ; i <= n; i++)
{
fact *= (i % MOD);
fact %= MOD;
}
return ( int )fact;
}
static int countWays( int n, int m)
{
return factMod(m);
}
public static void main(String args[])
{
int n = 2 , m = 2 ;
System.out.print(countWays(n, m));
}
}
|
Python3
MOD = 1000000007 ;
def factMod(n) :
fact = 1 ;
for i in range ( 2 , n + 1 ) :
fact * = (i % MOD);
fact % = MOD;
return fact;
def countWays(n, m) :
return factMod(m);
if __name__ = = "__main__" :
n = 2 ; m = 2 ;
print (countWays(n, m));
|
C#
using System;
class GFG
{
static int MOD = 1000000007;
static int factMod( int n)
{
int fact = 1;
for ( int i = 2; i <= n; i++)
{
fact *= (i % MOD);
fact %= MOD;
}
return fact;
}
static int countWays( int n, int m)
{
return factMod(m);
}
public static void Main()
{
int n = 2, m = 2;
Console.Write(countWays(n, m));
}
}
|
Javascript
<script>
MOD = 1000000007;
function factMod(n) {
var fact = 1;
for (i = 2; i <= n; i++) {
fact *= (i % MOD);
fact %= MOD;
}
return parseInt( fact);
}
function countWays(n , m) {
return factMod(m);
}
var n = 2, m = 2;
document.write(countWays(n, m));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)