1548. Subarray AND Grand Total

Medium3.5 points estimatedBit ManipulationCountingArray

A logistics team tags each crate on a belt with an integer permission code stored in the array nums. For every non-empty run of consecutive crates, the team computes the bitwise AND of its codes. Return the sum of these AND values over all runs; the total is returned as a 64-bit integer.

There are about n^2/2 runs, so enumerating them is too slow. Think per bit: a run keeps a given bit only if every crate in it has that bit, so the bit contributes inside each maximal block of crates that all carry it. Combine the blocks of each bit with the corresponding power of two.

Required complexity: O(20 * n) time and O(1) extra space. The answer is guaranteed to stay below 2^53.

Example 1

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

The runs give 3, 1, 2, 3&1=1, 1&2=0 and 3&1&2=0, which sum to 7.

Example 2

Input:
nums = [5,5]
Output:
15
Explanation:

The runs [5], [5] and [5,5] each have AND 5, so the total is 15.

Constraints

1 ≤ n ≤ 105

0 ≤ nums[i] < 220 (answer < 253)

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 M)
Space
O(1)

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…