


Given:
‘N’ = 2, ‘M’ = 3.
‘Hats’ = [[1, 2, 3],
[3, 4, 5]]
The answer will be 8, the combinations can be (1,3), (1,4), (1,5), (2,3), (2,4), (2,5), (3,4), (3,5).
The first line of input contains an integer ‘T’ denoting the number of test cases.
The first line of each test case contains two space-separated integers, ‘N,’ where ‘N’ is the number of rows in ‘HATS’ and ‘M’ where ‘M’ is the number of columns in ‘HATS’.
The next ‘N’ line of each test case contains ‘M’ space-separated integers, which tell the preference of hats of the ‘i’ the student.
For each test case, return the number of ways that the ‘N’ students wear different hats to each other. Since the answer may be too large, return it modulo 10 ^ 9 + 7.
You are not required to print the expected output; it has already been taken care of. Just implement the function.
1 <= ‘T’ <= 10
1 <= ‘N’ <= 10
1 <= ‘M’ <= 40
1 <= ‘HATS[i][j]’ <= 40
Time Limit: 1 sec.
In computing, numbers are internally represented in binary. This means, where we use an integer type for a variable, this will actually be represented internally as a summation of zeros and ones.
Bit masking allows us to use operations that work on bit-level.
You apply a mask to a value, wherein in our case, the value is our state 00000101, and a mask is again a binary number, which indicates the bits of interest.
The idea is, instead of thinking of a problem to assign hats to some students, think of assigning students to hats, that is, rehash the ‘HATS’ array such that we know what ‘HATS' have which student.
We represent the students as a bitmask, and all the bits are initially all the bits are off, representing that no students have been assigned any hats. At the end, if we set all the bits, we consider it as a valid combination, and our end goal is to count all valid combinations.
The steps are as follows:
Similar to the previous approach, It can be observed that there are recurring sub-problems. Therefore we can hash subproblems to speed up the recursion and better the time and space complexity.
The steps are as follows: