Sub topic 8
Hashing and Interning Strings
This chapter assumes you know the earlier chapters on immutability and string comparison. It also assumes you know how a hash table maps keys to buckets and what O(n) means.
Why strings get hashed
A hash function turns a string into a fixed-size integer. Hash tables use that integer to pick a bucket, so dict and set lookups can skip most comparisons. Strings are the most common hash-table keys, so their hashing cost matters.
Two rules apply to any hash function used this way:
- Equal strings must produce equal hashes.
- Different strings should rarely produce equal hashes. When they do, it is called a collision.
Immutability makes the first rule safe. If a key could change after insertion, its hash would change and the table would no longer find it.
A polynomial hash
A common design treats the characters as digits in a number system. Each step multiplies the running value by a base and adds the next character's code point.
def poly_hash(s, base=31, mod=1_000_000_007):
h = 0
for ch in s:
h = (h * base + ord(ch)) % mod
return h
print(poly_hash("abc")) # 96354
print(poly_hash("abd")) # 96355
print(poly_hash("abc") == poly_hash("abc")) # TrueFor "abc" the calculation is (97 * 31 + 98) * 31 + 99 = 96354. The loop reads every character once, so hashing costs O(n) for a string of length n. The Rabin-Karp chapter reuses this idea, because the formula allows a cheap update when a window slides along the text.
What a lookup really costs
Looking up a string key does two things. It computes the hash, then it compares the key against any entry in the same bucket.
The full comparison is O(n) in the worst case, because equal strings must be checked character by character. So a lookup is O(n) in the key length, not O(1). The "O(1) lookup" claim counts only the number of table probes.
Many runtimes soften this by caching the hash inside the string object. CPython and Java both do. Since the string cannot change, the hash is computed once, and later lookups with the same object read the stored value in O(1).
Hash randomization
Python's hash() for strings changes between runs unless PYTHONHASHSEED is fixed.
print(hash("hello")) # differs from one process to the nextThe reason is security. If an attacker knows the hash function, they can send many keys that land in one bucket. Each lookup then degrades toward O(n) comparisons per key, which can make a server very slow. A random seed per process prevents this attack.
Never store hash() output in a file or database, and never use it as a stable identifier. Use a fixed algorithm such as SHA-256 for that.
Interning
Interning keeps one canonical copy of each distinct string in a table. Every equal string then shares the same object. Two interned strings are equal exactly when they are the same object, so equality becomes a pointer comparison, which is O(1).
import sys
a = "".join(["data", "base"])
b = "".join(["data", "base"])
print(a == b) # True
print(a is b) # False, two separate objects
a = sys.intern(a)
b = sys.intern(b)
print(a is b) # True, both now point to the canonical copyInterning has costs:
- Each string needs a table lookup when it is interned, which hashes it once.
- The table uses memory, and the runtime must decide when a string can be released.
- Interning many unique, short-lived strings, such as user input, wastes both time and space.
It pays off when the same few values appear many times and are compared often. Examples are identifiers in a compiler, field names in parsed records, and enum-like labels.
Summary of costs
| Operation | Cost | Note |
|---|---|---|
| First hash of a string | O(n) | Reads every character |
| Later hash of the same object | O(1) | Cached in CPython and Java |
| Dictionary lookup with a matching key | O(n) | Final equality check |
| Equality of two interned strings | O(1) | Pointer comparison |
| Interning a string | O(n) | Hash plus table lookup |
Exercise
A program reads one million log lines and compares each line's level field ("INFO", "WARN", "ERROR") against a fixed set of values many times. Would interning the level field help, and why would interning the whole log line not?
Show answer
Interning the level field helps because only three distinct values exist, so the intern table stays tiny and each later comparison becomes an O(1) pointer check. Interning whole log lines would not help because nearly every line is unique. Each line would pay the O(n) hash and table insertion cost and add to the table's memory use, with almost no repeated comparisons to repay it.