Блог пользователя ajayNegi

Автор ajayNegi, история, 6 лет назад, По-английски

In a recent hiring challenge, a question was asked to find the no. of arrays of size N, whose xor of all the elements is 0 and the array should only contain 0,1,2,3,4,5 as its element. Return ans%(1e9+7). 1<=N<=1e5

Here are the test cases for the first 60 elements.

How should I approach this problem?

  • Проголосовать: нравится
  • -3
  • Проголосовать: не нравится

»
6 лет назад, скрыть # |
 
Проголосовать: нравится -10 Проголосовать: не нравится

What is N in this case? The size of the arrays?

»
6 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by ajayNegi (previous revision, new revision, compare).

»
6 лет назад, скрыть # |
 
Проголосовать: нравится -23 Проголосовать: не нравится
Hint
  • »
    »
    6 лет назад, скрыть # ^ |
     
    Проголосовать: нравится 0 Проголосовать: не нравится

    yeah, I know that. but my thoughts are quite brute force. I thought of iterating over the no. of 0s and for each iteration go over the no. of 1s and go on until 5 but this too bad. but, then 1^2^3 give 0 and 1^4^5 give 0 so I've to keep this in mind too.

    Then I thought of finding the combination of single occurrences of 0s + no. of pairs of (1,1), (2,2), (3,3), (4,4), (5,5) and + no. of triplets like (1,2,3), (1,4,5). But this again pushes me to iterate over the no. of occurrences of 0s and no. of pairs(which is 0(n^2).. bad) plus I've to keep in mind about the permutations(of 0s, 1s, 2s,..) too. So, it boiled down to find the no. of 0s, 1s, 2s, 3s, 4s, 5s and this is what I described in para 1.

»
6 лет назад, скрыть # |
 
Проголосовать: нравится +7 Проголосовать: не нравится

Use dp: notice that the xor sum will always be at most $$$7$$$ so we can calculate $$$dp[i][mask]$$$ which represents the number of arrays of length $$$i$$$ with xor sum of $$$mask$$$.

»
6 лет назад, скрыть # |
Rev. 2  
Проголосовать: нравится +5 Проголосовать: не нравится

you can solve it using dynamic programming where dp[i][j] = number of ways to form a sequence of length i whose xor is j. At each position you have only 6 choices so u can try all of them, let suppose at position i u choose k and you want your prefix xor to be j so u can calculate as : dp[i][j] += dp[i-1][k^j].

your final answer will be dp[n][0].

»
6 лет назад, скрыть # |
 
Проголосовать: нравится +25 Проголосовать: не нравится

Some extensions:

  • Solve for $$$N \leq 10^9$$$ if elements are in $$${0,1,2,3,4,5,6,7}$$$.
  • Solve for $$$N \leq 10^9$$$ with original values $$${0,1,2,3,4,5}$$$.
»
6 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится
»
6 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Will there be queries or only single test case? If there is no queries there is a sure dp solution.