Count Consistent Subarrays I Problem
#4111
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 4111.
You are given an integer array nums.
A subarray is called consistent if the bitwise AND of all its elements is equal to the minimum value of the subarray.
Return the number of consistent subarrays in nums.
Example 1:
Input: nums = [5,3,1,2]
Output: 6
Explanation:
The following subarrays are consistent:
Subarray Values Bitwise AND Minimum Value
nums[0..0] [5] 5 5
nums[1..1] [3] 3 3
nums[2..2] [1] 1 1
nums[3..3] [2] 2 2
nums[1..2] [3, 1] 3 AND 1 = 1 1
nums[0..2] [5, 3, 1] 5 AND 3 AND 1 = 1 1
Therefore, the number of consistent subarrays is 6.
Example 2:
Input: nums = [1,1,1]
Output: 6
Explanation:
For every subarray, both the bitwise AND and the minimum value are equal to 1. Therefore, the answer is 6.
Example 3:
Input: nums = [0]
Output: 1
Explanation:
The only subarray is [0], whose bitwise AND and minimum value are both 0. Therefore, the answer is 1.
Constraints:
1 <= nums.length <= 1000 <= nums[i] <= 100
Solution
Approach: Enumeration
Fix the left end i. Extend the right end j from i to the end while keeping the bitwise AND x and the minimum y of nums[i..j]; both start at nums[i]. After adding nums[j], set x &= nums[j] and y = min(y, nums[j]). The subarray is consistent exactly when x == y, so count it.
Complexity: O(n2) time and O(1) space, which is fine for n <= 100.
class Solution:
def countConsistent(self, nums: List[int]) -> int:
ans = 0
for i in range(len(nums)):
x = y = nums[i] # AND and minimum of nums[i..j]
for j in range(i, len(nums)):
x &= nums[j]
y = min(y, nums[j])
if x == y:
ans += 1
return ans