Number of Subarrays With AND Value of K - Problem

You are given an array of integers nums and a target integer k. Your mission is to find how many contiguous subarrays have a bitwise AND value that equals exactly k.

The bitwise AND operation combines all elements in a subarray using the & operator. For example, if we have a subarray [5, 3, 1], the bitwise AND would be 5 & 3 & 1 = 1.

Key insight: The AND operation is monotonic - adding more elements to a subarray can only make the AND result smaller or stay the same, never larger. This property is crucial for optimization!

Example: Given nums = [1, 1, 1] and k = 1, we have 6 valid subarrays: [1], [1], [1], [1,1], [1,1], and [1,1,1] - all have AND value of 1.

Input & Output

example_1.py — Simple Case
$ Input: nums = [1, 1, 1], k = 1
Output: 6
💡 Note: All subarrays have AND value 1: [1], [1], [1], [1,1], [1,1], [1,1,1]. Total: 6 subarrays.
example_2.py — Mixed Values
$ Input: nums = [1, 1, 2], k = 1
Output: 3
💡 Note: Valid subarrays: [1] (position 0), [1] (position 1), [1,1]. The subarray [1,1,2] has AND value 0, not 1.
example_3.py — No Valid Subarrays
$ Input: nums = [5, 3, 7], k = 2
Output: 0
💡 Note: No subarray has AND value 2. Individual elements: 5, 3, 7. Pairs: 5&3=1, 3&7=3, 5&7=5. All three: 5&3&7=1.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i], k ≤ 109
  • All integers fit in 32-bit representation
  • Subarrays must be contiguous

Visualization

Tap to expand
Bitwise AND Subarray VisualizationDigital Signal Processing Maze5Entry Point3Filter 11Filter 2Signal Processing:Path 1: [5] → Signal = 5Path 2: [5,3] → Signal = 5 & 3 = 1Path 3: [5,3,1] → Signal = 1 & 1 = 1 ✓At most 32 distinct signal levels possible!🎯 Key Insight: Monotonic property limits search space dramatically!
Understanding the Visualization
1
Enter the maze
Start with the first element as your signal strength
2
Apply filters
Each new element you encounter applies an AND filter
3
Track all paths
Maintain all possible signal strengths from different paths
4
Count target signals
Count how many paths produce exactly the target signal k
5
Optimize with insight
Use the fact that there are at most 32 distinct signal levels
Key Takeaway
🎯 Key Insight: The AND operation's monotonic property combined with the limited number of possible bit patterns (≤32) transforms an O(n²) problem into an efficient O(n × log(max_value)) solution.
Asked in
Google 12 Amazon 8 Meta 6 Microsoft 4
26.0K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen