Skip to content

String hashing

storing

Level 1 of 3

Also called Horner's rule and Polynomial string hash.

how it works

The idea on cat, as the watch page runs it.

A hash table needs a slot number for each key, and a word is no number. So read the word letter by letter, a as 1 up to z as 26. Start the value at 0. For each letter, multiply the value by 31 and add the letter's number. Then keep only the remainder after dividing by 13, the number of slots. The last value is the word's slot, from 0 to 12. Multiplying before each letter is Horner's rule. Never divided, cat would be 3 × 31 × 31, plus 1 × 31, plus 20, = 2,934: each letter is weighed by its place. This page counts letters read.

letternumbertimes 31 plus itremainder by 13
c30 × 31 + 3 = 33
a13 × 31 + 1 = 943
t203 × 31 + 20 = 1139
cat lands in slot 9. 94 is 7 thirteens and 3 over, and 113 is 8 thirteens and 9 over.
wordletters added upslot by addingslot by this method
listen7916
silent79112
Added up, two anagrams always share a slot. Multiplying first can part them, as it parts listen and silent. Not always, though: an and na share slot 6.
A short word: 8 moments of its 11 steps, the steps between them left for the watch page
  1. step 1 of 11

    cat#×31+#h0

    Turn cat into a slot from 0 to 12. Start with the value 0, and read the word one letter at a time.

    what it remembers to know where it is
    at letter
    not yet
    value so far
    0

    Where it says not yet, nothing is held there at that moment.

    watch from here

  2. step 3 of 11

    cat#×31+#h330

    Multiply the value 0 by 31 and add 3, giving 3.

    what it remembers to know where it is
    at letter
    1
    value so far
    0

    watch from here

  3. step 4 of 11

    cat#×31+#h3303

    3 divided by 13 leaves 3. Keep only that: the value is now 3.

    what it remembers to know where it is
    at letter
    1
    value so far
    3

    watch from here

  4. step 6 of 11

    cat#×31+#h3139403

    Multiply the value 3 by 31 and add 1, giving 94.

    what it remembers to know where it is
    at letter
    2
    value so far
    3

    watch from here

  5. step 7 of 11

    cat#×31+#h31394033

    94 divided by 13 leaves 3. Keep only that: the value is now 3.

    what it remembers to know where it is
    at letter
    2
    value so far
    3

    watch from here

  6. step 9 of 11

    cat#×31+#h3120394113033

    Multiply the value 3 by 31 and add 20, giving 113.

    what it remembers to know where it is
    at letter
    3
    value so far
    3

    watch from here

  7. step 10 of 11

    cat#×31+#h31203941130339

    113 divided by 13 leaves 9. Keep only that: the value is now 9.

    what it remembers to know where it is
    at letter
    3
    value so far
    9

    watch from here

  8. step 11 of 11

    cat#×31+#h31203941130339

    Every letter is read. cat goes in slot 9, after 3 letters, each one multiply, one add and one remainder.

    what it remembers to know where it is
    at letter
    3
    value so far
    9

    watch from here

the steps, in plain words
  1. start with the value 0Python line 8
  2. for each letter, from the first, read it as a number: a is 1 up to z is 26Python lines 9 and 10
  3. multiply the value by 31 and add the letter's numberPython line 11
  4. keep only the remainder after dividing by 13: that is the new valuePython line 12
  5. every letter read, so the value is the word's slot, from 0 to 12Python line 13
the same in Python

The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.

def string_hashing(word):
    """The slot of a word of letters a to z in a table of 13 slots, by Horner's rule.

    Each letter is read as a number, a is 1 up to z is 26. The value so far is
    multiplied by 31, the letter's number added, and only the remainder after
    dividing by 13 kept. Returns the last value, from 0 to 12.
    """
    value = 0
    for letter in word:  # each letter, from the first
        number = ord(letter) - ord("a") + 1  # a is 1 up to z is 26
        value = value * 31 + number  # times 31, plus the letter's number
        value = value % 13  # keep only the remainder after dividing by 13
    return value  # the word's slot

how it scales

The plot counts the letters the method reads on a word of nn letters, measured from 10 letters to 100,000.

Each dotted line up is ten times the one below, and each line across is ten times the one before. A count that grows in step with nn climbs one line up for each line across. The letters do: 10 letters read at 10, 100,000 at 100,000. Question 1 in section 4 works out why.

letters read, ten times more at each mark up

slope 1102104106101102103104105106107slope 1101102103104105106107101102103104105106107slope 1101102103104105106107101102103104105106107

nn, how many letters the word has, ten times more at each mark to the right

  • any word of nn letters, as every word of that length costs the samesolid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the work
how long these letters take, at a billion a second
nnletters readtime
1,0001,000about 1 microsecond
100,000100,000about 100 microseconds
10,000,00010,000,000about 10 milliseconds

The letters read are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.

make these counts yourself

Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.

"""Count string hashing's letters read yourself, as the plot on this page does.

Run it with Python 3.12 or later. For each n it prints the letters the method
reads on a word of n letters, the alphabet over and over, and the word's slot,
up to n = 100,000. The counts are the same on any computer; only the time
differs.
"""


def string_hashing(word):
    """The slot of a word of letters a to z in a table of 13 slots, by Horner's rule.

    Each letter is read as a number, a is 1 up to z is 26. The value so far is
    multiplied by 31, the letter's number added, and only the remainder after
    dividing by 13 kept. Returns the last value, from 0 to 12.
    """
    value = 0
    for letter in word:  # each letter, from the first
        number = ord(letter) - ord("a") + 1  # a is 1 up to z is 26
        value = value * 31 + number  # times 31, plus the letter's number
        value = value % 13  # keep only the remainder after dividing by 13
    return value  # the word's slot


def count(word):
    """The same method on word, counting each letter it reads."""
    value = 0
    letters = 0
    for letter in word:
        letters += 1
        value = (value * 31 + ord(letter) - ord("a") + 1) % 13
    return letters


if __name__ == "__main__":
    print(f"{'n':>7} {'letters':>8} {'slot':>5}")
    for n in (10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10_000, 20_000, 50_000, 100_000):
        word = ("abcdefghijklmnopqrstuvwxyz" * (n // 26 + 1))[:n]
        print(f"{n:>7} {count(word):>8} {string_hashing(word):>5}")

best, worst and average

Best, worst and average usually name different inputs of one size. Here every word of nn letters costs the same, whatever its letters: each is read once. So the table has one column, under the name worst.

A case is one kind of input. A bound says how fast its cost grows as nn grows.

The count is in the grid. Here it is nn alone, so every bound is of nn: O(n)O(n), Ω(n)\Omega(n) and Θ(n)\Theta(n).

what each case costs, and how fast that cost grows; section 4 works out every formula in it
worstany word of nn letters, as every word of that length costs the same
letters readnn
how the letters read grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)
ceiling, OOO(n)O(n)
floor, Ω\OmegaΩ(n)\Omega(n)

extra memory: the value so far, at most 12 × 31 + 26 = 398 before its remainder is kept, and the place of the letter being read

Extra memory is the room it needs on top of the input itself, while it runs.

wordlettersletters readsteps on the watch page
z115
cat3311
listen6620
Counted by the run. Each letter is 3 steps on the watch page, its number, times 31 plus it, and the remainder; then a start and an end.

where the formula comes from

Two questions, each worked line by line. Question 1 is the count the plot draws.

Question 1: how many letters, LL, does the method read on a word of nn letters?
  1. the move: one letter each time round

    the line:
    each time round, the loopreads the next letter, once\begin{gathered} \text{each time round, the loop} \\ \text{reads the next letter, once} \end{gathered}
    time roundletter readletters read so far
    1c1
    2a2
    3t3
    cat: 3 times round, 3 letters read.

    why it is allowed: The loop starts at the first letter and moves on one letter each time round, until the last. It never goes back.

  2. the move: count them

    the line:
    L=nL = n

    why it is allowed: By line 1, one letter read for each letter of the word. For cat, 3.

  3. the move: a ceiling

    the line:
    L≤nL \le n

    why it is allowed: By line 2, LL is nn, so at most nn.

  4. the move: read the bound

    the line:
    L∈O(n)L \in O(n)

    why it is allowed: By line 3: at most 1 times nn, at every nn.

  5. the move: a floor

    the line:
    L≥nL \ge n

    why it is allowed: By line 2 again, LL is nn, so at least nn.

  6. the move: read the bound

    the line:
    L∈Ω(n)L \in \Omega(n)

    why it is allowed: By line 5: at least 1 times nn, at every nn.

  7. the move: both together

    the line:
    L∈Θ(n)L \in \Theta(n)

    why it is allowed: Lines 4 and 6 bound LL by the same growth, nn, from above and below.

try it with a small nn: at n=3n = 3, line 2 gives L=3L = 3, which you can work out by hand

Question 2: the method keeps only the remainder after each letter. Why does it land in the slot the full value, never divided, would? Before cat's t, the full value is 13q+313q + 3: qq thirteens and 3 over.
  1. the move: never divided

    the line:
    never divided, cat is2,934, which leaves 9\begin{gathered} \text{never divided, cat is} \\ 2{,}934\text{, which leaves 9} \end{gathered}
    lettertotalnew totalc0× 31 +3=3a3× 31 +1=94t94× 31 +20=2,9342,934 = 225 × 13 + 9, slot9
    2,934 is 225 thirteens and 9 over, so cat goes in slot 9.

    why it is allowed: Never dividing, the full value after c, a and t is 3, 94 and 2,934. That is (3 × 31 + 1) × 31 + 20. It multiplies out to 3 × 31 × 31 + 1 × 31 + 20, just as 312 is 3 × 100 + 1 × 10 + 2. 2,934 is 225 thirteens and 9 over. The method kept 3, 3 and 9; its last total, 3 × 31 + 20 = 113, leaves 9 too.

  2. the move: the gap after t

    the line:
    D=(31(13q+3)+20)−(31×3+20)D = (31(13q + 3) + 20) - (31 \times 3 + 20)

    why it is allowed: Before t, the full value is 13q+313q + 3: 94 is 7 thirteens and 3 over, so qq is 7. The method keeps the 3 alone. Each is multiplied by 31 and t's 20 added. DD is how far apart the two totals land.

  3. the move: multiply out

    the line:
    D=31×13q+31×3+20−(31×3+20)\begin{gathered} D = 31 \times 13q + 31 \times 3 \\ + 20 - (31 \times 3 + 20) \end{gathered}

    why it is allowed: 31(13q+3)31(13q + 3) is 31×13q31 \times 13q plus 31×331 \times 3.

  4. the move: cancel

    the line:
    D=31×13qD = 31 \times 13q

    why it is allowed: 31×3+2031 \times 3 + 20 is added, then taken away.

  5. the move: count the 13s

    the line:
    D=13×31qD = 13 \times 31q

    why it is allowed: The same product in the other order. DD is a whole number of 13s, 31q31q of them. For cat, 217 thirteens, 2,821.

  6. the move: same remainder

    the line:
    113 is 8 thirteens and 9;2,934 is 217 thirteens more:225 thirteens and 9\begin{gathered} \text{113 is 8 thirteens and 9;} \\ \text{2,934 is 217 thirteens more:} \\ \text{225 thirteens and 9} \end{gathered}
    numberthirteensleft over
    11389
    2,8212170
    2,9342259
    2,934 is 113 plus 2,821, which is 217 thirteens by line 5.

    why it is allowed: Add 217 thirteens to 113: they join its 8 thirteens, and 9 is still under 13. So both leave 9. Any two numbers some 13s apart leave the same remainder, the same way.

  7. the move: any remainder, any letter

    the line:
    any kept r, any letter x:31r+x is added andtaken away, so D is 13×31q\begin{gathered} \text{any kept } r \text{, any letter } x\text{:} \\ 31r + x \text{ is added and} \\ \text{taken away, so } D \text{ is } 13 \times 31q \end{gathered}
    afterfull valuekept value13s more than kept
    c330
    a9437
    t2,9349225
    After every letter the full value is a whole number of 13s more than the kept one, so the last kept value, 9, is cat's slot.

    why it is allowed: Lines 2 to 5 with rr for the 3 kept, xx for t's 20, and qq for however many 13s. 31r+x31r + x is added and taken away, so the gap is still 13×31q13 \times 31q. By line 6, both totals leave the same remainder.

  8. the move: pass it on

    the line:
    after each letter: some13s plus the kept value\begin{gathered} \text{after each letter: some} \\ \text{13s plus the kept value} \end{gathered}

    why it is allowed: Before c, both are 0. By line 7, after each letter the full value leaves the same remainder as the method's total, and that remainder is the kept value. So the full value is some 13s plus the kept value, as 13q+313q + 3 was before t, and the same lines work at the next letter.

try it with a small qq: at q=7q = 7, line 2 gives D=2,821D = 2,821, which you can work out by hand

count it yourself

cat, step by step. Each letter is read once.

cat, every step written down
stepwhat happensletters read
1Turn cat into a slot from 0 to 12. Start with the value 0, and read the word one letter at a time.0
2Read c as the number 3, counting a as 1 up to z as 26.1
3Multiply the value 0 by 31 and add 3, giving 3.1
43 divided by 13 leaves 3. Keep only that: the value is now 3.1
5Read a as the number 1, counting a as 1 up to z as 26.2
6Multiply the value 3 by 31 and add 1, giving 94.2
794 divided by 13 leaves 3. Keep only that: the value is now 3.2
8Read t as the number 20, counting a as 1 up to z as 26.3
9Multiply the value 3 by 31 and add 20, giving 113.3
10113 divided by 13 leaves 9. Keep only that: the value is now 9.3
11Every letter is read. cat goes in slot 9, after 3 letters, each one multiply, one add and one remainder.3

In all, 3 letters read. The formula from section 4, nn, gives L=3L = 3 at n=3n = 3: the same.

where you meet it

Every hash table keyed by words turns the letters into a number first. The books, Java and Python each do it their own way.

  • the books' six surnames

    The books add up the computer's codes for the letters of six surnames, a capital R as 82 and a small a as 97. Rahman, Harman and Gerber all total 599, so they share a slot. With the same codes, multiplying by 31 before each letter and keeping the remainder by 13 puts the six in six slots (volume two, chapter 16).

    source: the books' volume two, chapter 16, Hashing things that are not numbers

  • Java's strings

    Java works out a string's number with the same base, 31: each character's code times 31 once for each character after it, all added up. A total past about 2 billion wraps round, as a car's odometer does. For ab, 97 times 31 plus 98. It keeps no remainder by 13; a table turns the number into a slot later.

    source: Java SE 21's documentation, String.hashCode (opens in a new tab))

  • Python's strings

    Python uses no fixed base for its strings. Its hash, SipHash, mixes in a secret random number chosen each time Python starts, unless the setting PYTHONHASHSEED fixes it. So a word can land in a different slot from one run to the next, and nobody can work out in advance words that all share one.

    source: Python's PEP 456, Secure and interchangeable hash algorithm (opens in a new tab), and its documentation of PYTHONHASHSEED (opens in a new tab)

surnameletter codes addedslot by addingslot by times 31
Rahman59915
Harman59919
Gerber59914
Adeyemi702012
Chen38257
Tanaka59278
The books' six surnames in 13 slots, each letter by its standard code, a capital R as 82 and a small a as 97. Adding puts three in slot 1.

what is used instead

Adding the letters reads as many letters, but every anagram shares a slot. Where someone might choose words to fill one slot, a function that mixes in a secret random number, such as Python's, is used instead.

how it compares

Three ways to turn a word into a slot among 13, each reading every letter once. Adding loses each letter's place. Times 13 loses every letter but the last. Times 31 keeps every letter and weighs it by its place, though some anagrams still share a slot, as an and na do.

wayletters readlistensilent
add the lettersnn11
times 31, plus the letternn612
times 13, plus the letternn17
Times 13 leaves only the last letter, as 13 times any value leaves 0 over. listen ends in n, 14, which leaves 1; silent ends in t, 20, which leaves 7. The books warn against a base that shares a factor with the table's size (volume two, chapter 16).