Sub topic 12
Tries and Suffix Arrays: Data Structures Built on Strings
This chapter assumes you know Python basics, dictionaries, binary search, and Big-O notation. It also assumes you have read the earlier chapters on string comparison and substring search. Strings can be the keys of a data structure, not only its contents. Two structures do this well: the trie for prefix lookups and the suffix array for substring lookups.
Tries: one character per level
A trie (also called a prefix tree) stores a set of words in a tree. Each edge is labeled with one character. A path from the root spells a prefix, and a marker on a node says "a word ends here."
The words "car" and "care" share the path c, a, r. Only the last step differs.
A dictionary-based trie
END = None # sentinel key that marks the end of a word
def insert(root, word):
node = root
for ch in word:
node = node.setdefault(ch, {})
node[END] = True
def starts_with(root, prefix):
node = root
for ch in prefix:
if ch not in node:
return False
node = node[ch]
return True
root = {}
for w in ["car", "care", "cat"]:
insert(root, w)
print(starts_with(root, "ca")) # True
print(starts_with(root, "dog")) # FalseEach node is a dictionary that maps a character to a child node. The END key is None, so it cannot collide with a real character.
Cost
Insert and lookup walk one level per character, so they take O(L) time, where L is the length of the word or prefix. The number of words stored does not matter. A hash set also gives O(L) average lookup for a whole word, because hashing reads every character. The trie's advantage is prefix queries. A hash set cannot answer "which words start with ca?" without scanning every word. A trie can walk to the ca node and list everything below it.
The cost is memory. Every node is its own dictionary object, so a trie with many words that share few prefixes can use far more memory than a plain list of the same words.
Suffix arrays: sorting every ending
A suffix array answers a different question: where does a pattern occur inside one long text? It is the list of starting positions of all suffixes of the text, ordered by the lexicographic order of those suffixes.
For "banana", the suffixes in sorted order are a, ana, anana, banana, na, nana. Their starting positions give the array [5, 3, 1, 0, 4, 2].
Every occurrence of a pattern is a prefix of some suffix. Sorted suffixes that start with the same pattern sit next to each other, so binary search can find them all.
import bisect
def build_suffix_array(s):
return sorted(range(len(s)), key=lambda i: s[i:])
def count_occurrences(s, sa, pattern):
m = len(pattern)
key = lambda i: s[i:i + m] # compare only the first m characters
lo = bisect.bisect_left(sa, pattern, key=key)
hi = bisect.bisect_right(sa, pattern, key=key)
return hi - lo
text = "banana"
sa = build_suffix_array(text)
print(sa) # [5, 3, 1, 0, 4, 2]
print(count_occurrences(text, sa, "ana")) # 2
print(count_occurrences(text, sa, "a")) # 3
print(count_occurrences(text, sa, "xyz")) # 0This code needs Python 3.10 or later, because bisect gained the key argument in that version.
Cost
Searching takes O(m log n) time for a pattern of length m in a text of length n. Each of the O(log n) binary search steps compares up to m characters.
The simple build above is slow. Sorting compares suffixes that can be long, and slicing s[i:] copies them, so the build can take O(n² log n) time and O(n²) temporary memory. Production libraries use algorithms such as SA-IS that build the array in O(n) time. The finished array stores only n integers.
Choosing between them
| Need | Better fit |
|---|---|
| Many words, prefix queries, autocomplete | Trie |
| One large text, many substring queries | Suffix array |
| Exact whole-word membership only | Hash set |
| Single search in a text you will not search again | Naive search, KMP, or Rabin-Karp |
Building a suffix array pays off only when you search the same text many times.
Exercise
A suffix array is built for the text "abab". What is the array, and how many times does "ab" occur according to the binary search?
Show answer
The suffixes are abab (0), bab (1), ab (2), and b (3). Sorted, they are ab (2), abab (0), b (3), bab (1), so the array is [2, 0, 3, 1]. Truncated to two characters, the sorted list is ab, ab, b, ba. The pattern "ab" matches the first two entries, so it occurs 2 times, at positions 2 and 0.
Exercise
You store 100,000 words in a trie. Does looking up a 6-letter word take longer than it would with 1,000 words?
Show answer
No. The lookup walks at most 6 levels, one per character, so it takes O(L) time with L = 6. The number of stored words does not change it.