bus_u_he's blog

By bus_u_he, history, 4 hours ago, In English

I recently took an OA with a question involving n arrays of size m. The task was to create an array A of size n by choosing one element from each array. Then, we had to find the minimum value of A0 | A1 | A2 | ... | An-1 (bitwise OR of all elements in A).

I used recursive DP, considering two options: either go forward in the same array or pick the current element and move to the start of the next array. However, this approach gave incorrect results for 3 out of 10 test cases. Can anyone help me identify what I missed or if I made an unforced error?

  • Vote: I like it
  • +8
  • Vote: I do not like it

»
4 hours ago, # |
  Vote: I like it 0 Vote: I do not like it

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

»
4 hours ago, # |
  Vote: I like it 0 Vote: I do not like it

Share your code

»
4 hours ago, # |
  Vote: I like it +6 Vote: I do not like it

If you managed to take some minimum value from the first array, that does not mean that it is the best idea to use that value. Ex: first array: [1, 2], second array: [2, 2]. If you take 1 from the first array because it is smaller, then you get the answer of 3, but the minimum value is 2.

One corect solution is as follows:

For each bit from most signifficant to least signifficant check if there is some element in each array that has that bit off. If so, then there is some way to pick the numbers so you don't have this bit set in the answer. Then you need to reduce each array. Remove the numbers that have that bit set since if you take them, you break the minimality.

If however there is some array where no element has the bit off then there is no way to get this bit off in the final solution. No array reduction is required, as you can take either on or off numbers without influencing this bit.

This way you build both the minimum value, and (can then build) all the posibilities (each array only has "useful" values at the end so picking any one of them from each array constitutes a good solution)

The time complexity is $$$O(N\cdot M\cdot \log A)$$$ where $$$A$$$ is the biggest value in the input.

  • »
    »
    3 hours ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    thanks a lot mate, now I know why I was wrong

»
115 minutes ago, # |
  Vote: I like it 0 Vote: I do not like it

what were the constraints? I have an O(32 * n * m * log(m)) algorithm. Idea is similar to above comment but I use sets, so additional log(m) factor.

»
10 minutes ago, # |
  Vote: I like it 0 Vote: I do not like it

for the 2nd if statement return INT_MAX instead of 1e7.

Input : 

1
4 4
434581591  366413825  351340371  81099756
443064262  783025542  980413631  511982969
956581993  979244577  507833677  890948799
808418018  212545955  683065029  351233430

Expected Output : 520093695

Your Output : 10000000