1534. Equal AND and OR Windows

Easy1.5 points estimatedBit ManipulationBrainteaserArray

An array nums of non-negative integers describes sensor flags. A window is a contiguous, non-empty block of the array. For a window, compute the bitwise AND of all its elements and the bitwise OR of all its elements.

Return the number of windows for which the AND equals the OR, as a long. Windows with the same positions count once each, even if their contents repeat elsewhere; a window of a single element always counts. Notice what it takes for AND and OR to coincide: every bit that is set in some element must be set in all of them.

Input: the array nums. Output: one integer. A single linear scan runs in O(n) time and O(1) extra space.

Example 1

Input:
nums = [3,3,5]
Output:
4
Explanation:

The windows [3], [3], [5] and [3,3] qualify, giving 4.

Example 2

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

Only the three single-element windows qualify.

Constraints

1 ≤ nums.length ≤ 1000

0 ≤ nums[i] ≤ 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 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
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…