Technique · CP 2000
Randomised Set Hashing (XOR / sum hashing, Zobrist)
Map every value to a random 64-bit number. The XOR or sum of those numbers fingerprints a set (or a multiset, with counts mod k). Questions like 'is this subarray a permutation' or 'does every value appear a multiple of 3 times' become prefix-hash equalities.
0/4 solved
Recognise it
The signal
subarrays that are permutations of 1..k
1Brute force
A frequency map per subarray: O(n2).
2The observation
Comparing sets element by element.
3Why it works
With random 64-bit labels, two distinct sets collide with probability about 2-64 per comparison, and prefix XOR/sum gives any subarray's hash in O(1).
Reach for it when
- +every value in the subarray occurs exactly k times / an even number of times
- +compare two multisets fast
- +identity checks on 2D regions
Not when
- ×anti-hash tests against a fixed seed (seed from time / random_device)
- ×you need the elements themselves, not just equality
Practice
- The Number of SubpermutationsCodeforces2500
- Three OccurrencesCodeforces2500
- The Untended AntiquityCodeforces2400
- Hyperregular Bracket StringsCodeforces2400
Pitfalls
Misconceptions
- !XOR cancels pairs, so it detects parity, not counts; use sums mod k or per-occurrence label cycling for 'exactly k'
Go deeper1 combinations · resources
Combinations
Randomised Set Hashing (XOR / sum hashing, Zobrist)+Prefix Sum+Two Pointers
subarrays that are permutations, or where every value occurs exactly k times
- Randomised Set Hashing (XOR / sum hashing, Zobrist):
- random labels make set identity additive
- Prefix Sum:
- a subarray's hash is a prefix difference/XOR
- Two Pointers:
- keep the window where no value exceeds k occurrences (1418G)