Number of Subarrays With AND Value of K - Problem
Given an array of integers nums and an integer k, return the number of subarrays of nums where the bitwise AND of the elements of the subarray equals k.
A subarray is a contiguous sequence of elements within an array.
The bitwise AND operation combines corresponding bits of integers using the AND logic gate. For example, 5 & 3 = 1 because 101 & 011 = 001.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [5,3,7,3], k = 3
›
Output:
3
💡 Note:
Subarrays with AND = 3: [3] at index 1, [7,3] from indices 2-3, and [3] at index 3. Note: 5&3=1, 3&7=3, 7&3=3.
Example 2 — Single Element
$
Input:
nums = [1,1,1], k = 1
›
Output:
6
💡 Note:
All subarrays have AND = 1: three single elements [1], two pairs [1,1], and one triplet [1,1,1]. Total: 3+2+1=6.
Example 3 — No Valid Subarrays
$
Input:
nums = [1,2,4], k = 8
›
Output:
0
💡 Note:
No subarray can have AND = 8 since the maximum element is 4, and AND operations can only make values smaller.
Constraints
- 1 ≤ nums.length ≤ 105
- 0 ≤ nums[i] ≤ 109
- 0 ≤ k ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [5,3,7,3] and target k=3
2
Process
Check all subarrays and compute AND values
3
Output
Count of subarrays with AND = k
Key Takeaway
🎯 Key Insight: AND operations can only decrease values, so we can efficiently prune impossible branches
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code