1801. OR Target Selections
A lab has n sensor modules, and module i reports a 16-bit status word nums[i]. A selection is any subset of module indices, and the empty selection is allowed with combined word 0. The combined word of a selection is the bitwise OR of the chosen status words. Return the number of selections whose combined word is exactly target, modulo 1000000007. Selections are different when their index sets differ, so equal values at different indices count separately.
Only words whose set bits all lie inside target can ever be used. Do not test subsets one by one: count how many words are submasks of each mask with a sum-over-subsets pass, then use inclusion-exclusion over the submasks of target. The intended cost is about O(n + 16 * 2^16) time and O(n + 2^16) space.
Example 1
- Input:
- nums = [1,2,3], target = 3
- Output:
- 5
- Explanation:
Subsets {3}, {1,2}, {1,3}, {2,3} and {1,2,3} all OR to 3, so there are 5.
Example 2
- Input:
- nums = [0,0], target = 0
- Output:
- 4
- Explanation:
Every one of the 4 subsets, including the empty one, ORs to 0.
Example 3
- Input:
- nums = [5,1,4], target = 5
- Output:
- 5
- Explanation:
Subsets {5}, {5,1}, {5,4}, {5,1,4} and {1,4} all OR to 5, giving 5.
Constraints
1 ≤ n ≤ 105
0 ≤ nums[i], target < 216
Answer modulo 1000000007
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n + B * 2^B), B = 16
- Space
- O(n + 2^B)