1546. OR Exactly K Windows

Medium3.5 points estimatedBit ManipulationArrayHash Table

A switchboard logs which circuits were active in each time slot as bitmasks in the array nums. A window of consecutive slots is complete when the bitwise OR of all masks inside it equals exactly the target mask k: no circuit outside k is lit and every circuit of k appears at least once.

Return the number of non-empty contiguous windows whose OR is exactly k. For example, [1, 2, 3] with k = 3 has 4 such windows. Windows with different positions are counted separately even if they look alike.

Brute force over all windows is quadratic. Note that OR only ever adds bits as a window grows to the left, so for a fixed right end the windows share at most 31 distinct OR values. Keep a short list of (OR value, number of starts) from one right end to the next and add the count whose value is k. This runs in O(n * 31) time with O(31) extra space, and the answer needs a 64-bit integer.

Example 1

Input:
nums = [1,2,3], k = 3
Output:
4
Explanation:

Windows [3], [1,2], [2,3] and [1,2,3] have OR 3, while [1] and [2] do not, so the answer is 4.

Example 2

Input:
nums = [4,4,4], k = 4
Output:
6
Explanation:

Every window of the three equal masks has OR 4, and there are 6 windows.

Constraints

1 ≤ nums.length ≤ 105; 0 ≤ nums[i], k ≤ 109

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 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n log C)
Space
O(log C)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…