Technique · Interview · hard
Few Distinct Subarray OR / AND / GCD Values
For a fixed right end i, the OR (AND, GCD) of a[j..i] changes at most log2(V) times as j moves left, because each change adds a bit (removes a bit, or at least halves the gcd). Keep the list of (value, leftmost j) for i - 1 and extend it to i.
0/7 solved
Recognise it
The signal
count distinct ORs/ANDs over all subarrays
1Brute force
All subarrays: O(n2).
2The observation
There are O(n2) subarrays but only O(n log V) distinct (value, right end) pairs.
3Why it works
The list for right end i is strictly monotone in value and has at most log V + 1 entries.
Reach for it when
- +subarray whose OR/AND is closest to k
- +number of subarrays whose GCD/AND equals k
- +for each i, the shortest subarray reaching the maximum OR
Not when
- ×the operation is sum or XOR (nothing saturates; use prefix sums / prefix XOR)
Practice
Pitfalls
Misconceptions
- !a sliding window over OR needs per-bit counts to undo; the list method needs no undo at all
Go deeper2 combinations · resources
Combinations
Few Distinct Subarray OR / AND / GCD Values+Hash Map / Hash Set Lookup
distinct subarray ORs, or the number of subarrays with AND equal to k
- Few Distinct Subarray OR / AND / GCD Values:
- at most log V distinct OR/AND values end at each index
- Hash Map / Hash Set Lookup:
- collect the distinct values, or count those equal to k
Bitwise ORs of SubarraysNumber of Subarrays With AND Value of K
Few Distinct Subarray OR / AND / GCD Values+GCD / LCM & Euclid+Hash Map / Hash Set Lookup
the number of subarrays whose gcd equals x, for many x
- Few Distinct Subarray OR / AND / GCD Values:
- O(log V) (gcd, count) pairs per right end
- GCD / LCM & Euclid:
- the gcd as j moves left only drops to a divisor
- Hash Map / Hash Set Lookup:
- global count of subarrays per gcd value