Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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.
Example 1:
Input: nums = [1,1,1], k = 1
Output: 6
Explanation:
All subarrays contain only 1's.
Example 2:
Input: nums = [1,1,2], k = 1
Output: 3
Explanation:
Subarrays having an AND value of 1 are: [1,1,2], [1,1,2], [1,1,2].
Example 3:
Input: nums = [1,2,3], k = 2
Output: 2
Explanation:
Subarrays having an AND value of 2 are: [1,2,3], [1,2,3].
Constraints:
1 <= nums.length <= 1050 <= nums[i], k <= 109Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search · Bit Manipulation · Segment Tree
[1,1,1] 1
[1,1,2] 1
[1,2,3] 2
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3209: Number of Subarrays With AND Value of K
class Solution {
public long countSubarrays(int[] nums, int k) {
long ans = 0;
Map<Integer, Integer> pre = new HashMap<>();
for (int x : nums) {
Map<Integer, Integer> cur = new HashMap<>();
for (var e : pre.entrySet()) {
int y = e.getKey(), v = e.getValue();
cur.merge(x & y, v, Integer::sum);
}
cur.merge(x, 1, Integer::sum);
ans += cur.getOrDefault(k, 0);
pre = cur;
}
return ans;
}
}
// Accepted solution for LeetCode #3209: Number of Subarrays With AND Value of K
func countSubarrays(nums []int, k int) (ans int64) {
pre := map[int]int{}
for _, x := range nums {
cur := map[int]int{}
for y, v := range pre {
cur[x&y] += v
}
cur[x]++
ans += int64(cur[k])
pre = cur
}
return
}
# Accepted solution for LeetCode #3209: Number of Subarrays With AND Value of K
class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
ans = 0
pre = Counter()
for x in nums:
cur = Counter()
for y, v in pre.items():
cur[x & y] += v
cur[x] += 1
ans += cur[k]
pre = cur
return ans
// Accepted solution for LeetCode #3209: Number of Subarrays With AND Value of K
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3209: Number of Subarrays With AND Value of K
// class Solution {
// public long countSubarrays(int[] nums, int k) {
// long ans = 0;
// Map<Integer, Integer> pre = new HashMap<>();
// for (int x : nums) {
// Map<Integer, Integer> cur = new HashMap<>();
// for (var e : pre.entrySet()) {
// int y = e.getKey(), v = e.getValue();
// cur.merge(x & y, v, Integer::sum);
// }
// cur.merge(x, 1, Integer::sum);
// ans += cur.getOrDefault(k, 0);
// pre = cur;
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #3209: Number of Subarrays With AND Value of K
function countSubarrays(nums: number[], k: number): number {
let ans = 0;
let pre = new Map<number, number>();
for (const x of nums) {
const cur = new Map<number, number>();
for (const [y, v] of pre) {
const z = x & y;
cur.set(z, (cur.get(z) || 0) + v);
}
cur.set(x, (cur.get(x) || 0) + 1);
ans += cur.get(k) || 0;
pre = cur;
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.