String hashing
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.
| letter | number | times 31 plus it | remainder by 13 |
|---|---|---|---|
| c | 3 | 0 × 31 + 3 = 3 | 3 |
| a | 1 | 3 × 31 + 1 = 94 | 3 |
| t | 20 | 3 × 31 + 20 = 113 | 9 |
| word | letters added up | slot by adding | slot by this method |
|---|---|---|---|
| listen | 79 | 1 | 6 |
| silent | 79 | 1 | 12 |
step 1 of 11
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.
step 3 of 11
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
step 4 of 11
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
step 6 of 11
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
step 7 of 11
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
step 9 of 11
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
step 10 of 11
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
step 11 of 11
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
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- start with the value 0Python line 8
- for each letter, from the first, read it as a number: a is 1 up to z is 26Python lines 9 and 10
- multiply the value by 31 and add the letter's numberPython line 11
- keep only the remainder after dividing by 13: that is the new valuePython line 12
- 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 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 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
, how many letters the word has, ten times more at each mark to the right
- any word of 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
| letters read | time | |
|---|---|---|
| 1,000 | 1,000 | about 1 microsecond |
| 100,000 | 100,000 | about 100 microseconds |
| 10,000,000 | 10,000,000 | about 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 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 grows.
The count is in the grid. Here it is alone, so every bound is of : , and .
| worstany word of letters, as every word of that length costs the same | |
|---|---|
| letters read | |
| how the letters read grow in each case | |
| tight, | |
| ceiling, | |
| floor, | |
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.
| word | letters | letters read | steps on the watch page |
|---|---|---|---|
| z | 1 | 1 | 5 |
| cat | 3 | 3 | 11 |
| listen | 6 | 6 | 20 |
where the formula comes from
Two questions, each worked line by line. Question 1 is the count the plot draws.
the move: one letter each time round
the line:time round letter read letters read so far 1 c 1 2 a 2 3 t 3 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.
the move: count them
the line:why it is allowed: By line 1, one letter read for each letter of the word. For cat, 3.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 2, is , so at most .
guess it, thenthe move: read the bound
the line:why it is allowed: By line 3: at most 1 times , at every .
guess it, thenthe move: a floor
the line:why it is allowed: By line 2 again, is , so at least .
guess it, thenthe move: read the bound
the line:why it is allowed: By line 5: at least 1 times , at every .
guess it, thenthe move: both together
the line:why it is allowed: Lines 4 and 6 bound by the same growth, , from above and below.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: never divided
the line: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.
the move: the gap after t
the line:why it is allowed: Before t, the full value is : 94 is 7 thirteens and 3 over, so is 7. The method keeps the 3 alone. Each is multiplied by 31 and t's 20 added. is how far apart the two totals land.
guess it, thenthe move: multiply out
the line:why it is allowed: is plus .
guess it, thenthe move: cancel
the line:why it is allowed: is added, then taken away.
guess it, thenthe move: count the 13s
the line:why it is allowed: The same product in the other order. is a whole number of 13s, of them. For cat, 217 thirteens, 2,821.
guess it, thenthe move: same remainder
the line:number thirteens left over 113 8 9 2,821 217 0 2,934 225 9 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.
guess it, thenthe move: any remainder, any letter
the line:after full value kept value 13s more than kept c 3 3 0 a 94 3 7 t 2,934 9 225 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 for the 3 kept, for t's 20, and for however many 13s. is added and taken away, so the gap is still . By line 6, both totals leave the same remainder.
guess it, thenthe move: pass it on
the line: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 was before t, and the same lines work at the next letter.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
count it yourself
cat, step by step. Each letter is read once.
| step | what happens | letters read |
|---|---|---|
| 1 | Turn cat into a slot from 0 to 12. Start with the value 0, and read the word one letter at a time. | 0 |
| 2 | Read c as the number 3, counting a as 1 up to z as 26. | 1 |
| 3 | Multiply the value 0 by 31 and add 3, giving 3. | 1 |
| 4 | 3 divided by 13 leaves 3. Keep only that: the value is now 3. | 1 |
| 5 | Read a as the number 1, counting a as 1 up to z as 26. | 2 |
| 6 | Multiply the value 3 by 31 and add 1, giving 94. | 2 |
| 7 | 94 divided by 13 leaves 3. Keep only that: the value is now 3. | 2 |
| 8 | Read t as the number 20, counting a as 1 up to z as 26. | 3 |
| 9 | Multiply the value 3 by 31 and add 20, giving 113. | 3 |
| 10 | 113 divided by 13 leaves 9. Keep only that: the value is now 9. | 3 |
| 11 | Every 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, , gives at : 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)
| surname | letter codes added | slot by adding | slot by times 31 |
|---|---|---|---|
| Rahman | 599 | 1 | 5 |
| Harman | 599 | 1 | 9 |
| Gerber | 599 | 1 | 4 |
| Adeyemi | 702 | 0 | 12 |
| Chen | 382 | 5 | 7 |
| Tanaka | 592 | 7 | 8 |
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.
| way | letters read | listen | silent |
|---|---|---|---|
| add the letters | 1 | 1 | |
| times 31, plus the letter | 6 | 12 | |
| times 13, plus the letter | 1 | 7 |