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: 5
💡 Note: Subarrays with AND = 3: [3] at index 1, [3,7] from indices 1-2, [7,3] from indices 2-3, [3] at index 3, and [3,7,3] from indices 1-3. Total: 5 subarrays.
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
Subarrays With AND Value of K INPUT nums array: 5 101 3 011 7 111 3 011 i=0 i=1 i=2 i=3 Target k = 3 Binary: 011 Goal: Find all subarrays where AND of elements = k Subarrays to check: [5], [5,3], [5,3,7]... [3], [3,7], [7,3]... Total: 10 subarrays ALGORITHM STEPS 1 Track AND values Maintain set of AND results ending at i 2 Extend subarrays For each num, AND with all previous results 3 Count matches When AND == k, increment counter 4 Key optimization AND only decreases, limited unique values Valid Subarrays (AND=3): [3] at i=1 [7,3]: 7 AND 3 = 3 [3] at i=3 Count: 3 FINAL RESULT 3 subarrays Valid Subarrays: [3] (i=1) 3 = 3 OK [7,3] (i=2,3) 7 AND 3 = 3 OK [3] (i=3) 3 = 3 OK All other subarrays have AND != 3 Time: O(n * log(max)) Key Insight: The AND operation can only keep bits or turn them off - it never increases. This means as we extend a subarray, AND values monotonically decrease. For any position, there are at most O(log(max_val)) distinct AND values, allowing us to efficiently track all possible subarray AND results. TutorialsPoint - Number of Subarrays With AND Value of K | Optimized AND Calculation
Asked in
Google 25 Microsoft 18 Amazon 15 Meta 12
23.4K Views
Medium Frequency
~35 min Avg. Time
892 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