Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Arrays & Two Pointers/Hash Map / Hash Set Lookup

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.

Learn firstHash Map / Hash Set LookupPrefix SumBit Tricks & Bitmasking
0%
mastery
0/4 solved
Practise nextThe Number of Subpermutations
IdeaPracticePitfalls

Recognise it

The signal

subarrays that are permutations of 1..k

  1. 1Brute force

    A frequency map per subarray: O(n2).

  2. 2The observation

    Comparing sets element by element.

  3. 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

Next

The Number of Subpermutations

0/4 solved
  • 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)

    The Number of SubpermutationsThree Occurrences

Resources

  • Two PointersUSACO Guide · course
  • Prefix SumsUSACO Guide · course
  • More on Prefix Sums (difference arrays)USACO Guide · course
  • Array cheatsheetTech Interview Handbook · article
  • NeetCode RoadmapNeetCode · sheet
  • Array and String explore cardLeetCode · course
TodayReviewPatternsProblems