AlgoTales · Roadmap

String hashing

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

String hashing turns any piece of text into one small number, a fingerprint, so the same text always gives the same number and different texts almost always give different ones. Comparing two short numbers is far quicker than comparing two long texts, which is why it shows up everywhere in apps.

Practical use cases

  • Web app: Skip re-uploading an unchanged file. A photo-backup page lets users drop a folder of 2,000 pictures every week. The browser computes a fingerprint of each file and sends only the fingerprints first; the server replies with the ones it has never seen. Only the 30 new pictures travel over the network, so a ten-minute upload becomes a few seconds.
  • Web app: Spotting duplicate blog posts or listings. A classifieds site keeps getting the same ad pasted by different users. Instead of comparing every new ad word by word against thousands of old ones, you store a fingerprint of the cleaned-up text in an indexed column. A new ad is rejected when its fingerprint already exists, and the check takes one lookup.
  • System: Password storage and cache keys. A login system never saves your password, only a fingerprint of it, so a leaked table does not reveal the real words. Caches use the same idea: the long URL plus query string is turned into a short fixed-size key so the lookup stays quick no matter how long the original text was.

The story: The Fingerprint Counter at the Chai Stall

Raju's chai stall became so popular that customers left long messages on the order slips: "Less sugar, more ginger, extra hot, no cream". His helper Aarav had to check whether two slips held the same order, and reading two long lines letter by letter took forever at lunch rush.

Mira suggested a fingerprint. "Turn every order into one small number using a fixed recipe. If two slips give different numbers, the orders are definitely different, and you do not have to read them. If the numbers match, look closer to be sure." The recipe: go through the letters, and at each letter, stretch the number you have so far, add this letter's value, and wrap it with a clock-style remainder so it never grows too big.

Aarav tried it on TEA, EAT and ATE. The letters were the same, but the three numbers were different, because the stretching made a letter's position matter. This is string hashing: squeeze any string into a small number. Two rules to remember: the same string always gives the same number, and different strings usually (but not always!) give different numbers. A rare clash is called a collision.

How to spot this problem, and where you need it

You keep comparing long pieces of text with each other, or searching for the same text again and again, and the work grows with the length and the number of texts.

Signs you need it

  • You are comparing whole strings, files or paragraphs against a big collection just to learn "have I seen this exact thing before?".
  • A problem asks for duplicates, anagram groups, equal substrings or "does this text appear in that one" and a plain nested loop is too slow.
  • Your code uses long text as a lookup key or database column and queries on it feel sluggish.

Where to use it in a project

  • Duplicate detection for uploads, product listings, support tickets or imported CSV rows.
  • Cache keys for pages or API responses built from a long URL and its parameters.
  • Checking whether a downloaded file or a saved config changed since last time.

The solution

Run each text through a hash function that gives back a fixed-size number. Store or compare that number instead of the text. If two numbers differ, the texts are definitely different; if they match, you can optionally do one full comparison to be certain. Because the number has the same small size whatever the text length, lookups and comparisons stay cheap.

Payoff: Before: comparing a new ad with 50,000 old ones word by word. After: one fingerprint lookup, answered instantly even as the table grows.

Explain it like I am 8

Imagine a magic machine that eats any word and spits out a small number, like a fingerprint. The same word always gives the same number. Two different words almost always give different numbers, so comparing numbers is a super-quick way to say "these are probably different".

How it works, step by step

  1. Give each letter a number (A=1, B=2…, or its character code).
  2. Start with 0 as your running fingerprint.
  3. For each letter: stretch the running number (multiply by a base such as 31), add the letter's number.
  4. Wrap it with a remainder (% M) so the number stays small, like hours on a clock.
  5. Compare fingerprints first. Different means different. Equal means "probably the same", so verify if it truly matters.

The code in four languages

PHP

<?php
// A tiny polynomial string hash: stretch, add, wrap.
function stringHash(string $s, int $base = 31, int $mod = 101): int {
    $h = 0;
    for ($i = 0; $i < strlen($s); $i++) {
        $value = ord($s[$i]) - 64;                 // A=1, B=2, ... (uppercase only)
        $h = ($h * $base + $value) % $mod;         // stretch, add, wrap like a clock
    }
    return $h;
}

foreach (["TEA", "EAT", "ATE", "TEA"] as $w) {
    echo $w . " => " . stringHash($w) . "\n";
}

// Use the fingerprint as a quick filter before a full compare.
function probablySame(string $a, string $b): bool {
    if (stringHash($a) !== stringHash($b)) {
        return false;                              // definitely different, no need to read on
    }
    return $a === $b;                              // equal hashes: confirm to rule out a collision
}
echo var_export(probablySame("TEA", "EAT"), true) . "\n";    // false
echo var_export(probablySame("TEA", "TEA"), true) . "\n";    // true

JavaScript

// A tiny polynomial string hash: stretch, add, wrap.
function stringHash(s, base = 31, mod = 101) {
  let h = 0;
  for (let i = 0; i < s.length; i++) {
    const value = s.charCodeAt(i) - 64;            // A=1, B=2, ... (uppercase only)
    h = (h * base + value) % mod;                  // stretch, add, wrap like a clock
  }
  return h;
}

for (const w of ['TEA', 'EAT', 'ATE', 'TEA']) {
  console.log(w + ' => ' + stringHash(w));
}

// Use the fingerprint as a quick filter before a full compare.
function probablySame(a, b) {
  if (stringHash(a) !== stringHash(b)) {
    return false;                                  // definitely different, no need to read on
  }
  return a === b;                                  // equal hashes: confirm to rule out a collision
}
console.log(probablySame('TEA', 'EAT'));           // false
console.log(probablySame('TEA', 'TEA'));           // true

Java

public class Main {
    // A tiny polynomial string hash: stretch, add, wrap.
    static int stringHash(String s) {
        int base = 31;
        int mod = 101;
        int h = 0;
        for (int i = 0; i < s.length(); i++) {
            int value = s.charAt(i) - 64;              // A=1, B=2, ... (uppercase only)
            h = (h * base + value) % mod;              // stretch, add, wrap like a clock
        }
        return h;
    }

    // Use the fingerprint as a quick filter before a full compare.
    static boolean probablySame(String a, String b) {
        if (stringHash(a) != stringHash(b)) {
            return false;                              // definitely different, no need to read on
        }
        return a.equals(b);                            // equal hashes: confirm to rule out a collision
    }

    public static void main(String[] args) {
        for (String w : new String[]{"TEA", "EAT", "ATE", "TEA"}) {
            System.out.println(w + " => " + stringHash(w));
        }
        System.out.println(probablySame("TEA", "EAT"));    // false
        System.out.println(probablySame("TEA", "TEA"));    // true
    }
}

Go

package main

import "fmt"

// stringHash is a tiny polynomial string hash: stretch, add, wrap.
func stringHash(s string) int {
	const base = 31
	const mod = 101
	h := 0
	for i := 0; i < len(s); i++ {
		value := int(s[i]) - 64    // A=1, B=2, ... (uppercase only)
		h = (h*base + value) % mod // stretch, add, wrap like a clock
	}
	return h
}

// probablySame uses the fingerprint as a quick filter before a full compare.
func probablySame(a, b string) bool {
	if stringHash(a) != stringHash(b) {
		return false // definitely different, no need to read on
	}
	return a == b // equal hashes: confirm to rule out a collision
}

func main() {
	for _, w := range []string{"TEA", "EAT", "ATE", "TEA"} {
		fmt.Println(w, "=>", stringHash(w))
	}
	fmt.Println(probablySame("TEA", "EAT")) // false
	fmt.Println(probablySame("TEA", "TEA")) // true
}

Time: O(n) to hash a string of n letters · Extra space: O(1). Computing the fingerprint reads each letter once; comparing two fingerprints afterwards is a single O(1) check.

Watch out for

  • Believing equal hashes prove equal strings. Collisions exist (two words can share a fingerprint), so verify when correctness matters.
  • Using a hash that ignores order (like just adding letter values), which makes TEA, EAT and ATE collide on purpose.
  • Letting the number grow without a wrap. It overflows quickly, so always reduce with a modulus.

Quick check

  1. Two strings have different hashes. What do we know?
    • They are probably the same
    • They are definitely different
    • Nothing
  2. Two strings have the same hash. What do we know?
    • They are certainly equal
    • They are anagrams
    • They might be equal, but could be a collision
  3. Why does the recipe stretch the number before adding each letter?
    • To make positions matter
    • To make it faster
    • To sort the letters