---
id: hashing
title: "Hashing"
author: Benjamin Qi
description: Quickly test equality of substrings with a small probability of failure.
frequency: 1
---

import { Problem } from "../models";

export const metadata = {
  problems: {
    ex: [
      new Problem("Gold", "Cownomics", "741", "Easy", false, [], ""),
    ],
    general: [
      new Problem("CSA", "Palindromic Partitions", "palindromic-partitions", "Easy", false, ["Greedy", "Hashing"], ""),
      new Problem("CF", "Palindromic Characteristics", "problemset/problem/835/D", "Easy", false, ["DP", "Hashing"], ""),
      new Problem("CF", "Liar", "problemset/problem/822/E", "Hard", false, ["DP", "Hashing"], ""),
    ],
    adj: [
      new Problem("CF", "Berland SU Computer Network", "contest/847/problem/L", "Normal", false, [], ""),
    ]
  }
};

## Tutorial

<resources>
  <resource source="CPH" title="26.3 - String Hashing" starred>good intro</resource>
  <resource source="cp-algo" title="String Hashing" url="string/string-hashing.html" starred>code</resource>
  <resource source="PAPS" title="14.3 - Hashing" starred>many applications</resource>

</resources>

My implementation can be found [here](https://github.com/bqi343/USACO/blob/master/Implementations/content/strings%20(14)/Light/HashRange%20(14.2).h). It uses two bases rather than just one to decrease the probability that two random strings hash to the same value. As mentioned in the articles above, there is no need to calculate modular inverses.

## Example: Cownomics (Gold)

<problems-list problems={metadata.problems.ex} />

  - Use two pointers; for a fixed $l$, keep extending $r$ to the right until the positions $l\ldots r$ explain spotiness. 
  - Hashing gives you a way to quickly check whether two substrings of different cow types are equal. So for a single $[l,r]$ pair you can check whether it works in $O(N\log N)$ time (and you only need to check $O(M)$ of these pairs in total).
  - Actually, it's possible to pass $O(N^2M)$ (or even slower) solutions.

## Adjacency Lists

(elaborate)

<problems-list problems={metadata.problems.adj} />

## Hacking

<resources>
  <resource source="CF" title="dacin21 - Anti-Hash Tests" url="blog/entry/60442">On CF educational rounds in particular, make sure to randomize your bases.</resource>
</resources>

## Problems

<problems-list problems={metadata.problems.general} />

