#3209
Number of Subarrays With AND Value of K
HardArrayBinary SearchBit ManipulationSegment TreeHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a sliding window approach combined with bit manipulation to efficiently count valid subarrays. This reduces unnecessary calculations and leverages properties of the AND operation.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a variable to count valid subarrays and a pointer for the right end of the window.
- 2Step 2: Iterate through the array with a left pointer, maintaining a right pointer to extend the window.
- 3Step 3: For each left pointer position, reset the AND value and move the right pointer to find valid subarrays.
- 4Step 4: If the AND value equals k, count all subarrays ending at the right pointer.
- 5Step 5: Move the left pointer and repeat until all positions are checked.
solution.py14 lines
1def countSubarrays(nums, k):
2 count = 0
3 n = len(nums)
4 for left in range(n):
5 and_value = nums[left]
6 if and_value == k:
7 count += 1
8 for right in range(left + 1, n):
9 and_value &= nums[right]
10 if and_value == k:
11 count += 1
12 if and_value < k:
13 break
14 return countℹ
Complexity note: The time complexity is O(n) because we efficiently traverse the array while maintaining a running AND value. The space complexity is O(1) as we only use a few variables for counting.
- 1The AND operation can only reduce or maintain the value, never increase it.
- 2If the AND value drops below k, further elements will not help, allowing us to break early.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.