Skip to content

Commit 4bd43e4

Browse files
committed
refactor(strings): address suffix array review comments
- add a doctest cross-checking the result against a naive sort - compare neighbouring sorted keys when renumbering instead of rebuilding the rank pairs - document the node bound against suffix trees and the O(n log^2 n) cost against linear-time constructions - explain the tie-breaking index - run the doctests under __main__
1 parent 1e02eda commit 4bd43e4

1 file changed

Lines changed: 24 additions & 14 deletions

File tree

‎strings/suffix_array.py‎

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,13 @@
33
https://cp-algorithms.com/string/suffix-array.html
44
55
A suffix array lists the starting positions of every suffix of a string in
6-
lexicographic order. It needs one integer per suffix, where a suffix tree
7-
needs a node per character, so it is the compact structure used for pattern
8-
search and for the LCP-based algorithms built on top of it.
6+
lexicographic order. It needs one integer per suffix, while a suffix tree
7+
needs up to 2n nodes, so it is the compact structure used for pattern search
8+
and for the LCP-based algorithms built on top of it.
99
10-
Construction here uses prefix doubling (Manber-Myers).
10+
Construction here uses prefix doubling (Manber-Myers). It is simpler and much
11+
lighter in memory than the linear-time constructions (Ukkonen for suffix
12+
trees, SA-IS for suffix arrays), but runs slower: O(n log² n) instead of O(n).
1113
1214
Time Complexity: O(n log² n) - where n is the length of the text
1315
Space Complexity: O(n)
@@ -33,6 +35,11 @@ def suffix_array(text: str) -> list[int]:
3335
[0]
3436
>>> suffix_array("")
3537
[]
38+
>>> all(
39+
... suffix_array(s) == sorted(range(len(s)), key=lambda i: s[i:])
40+
... for s in ("aaaa", "abab", "banana", "mississippi", "abracadabra")
41+
... )
42+
True
3643
"""
3744
n = len(text)
3845
if n == 0:
@@ -48,25 +55,22 @@ def suffix_array(text: str) -> list[int]:
4855
# Sort by the first 2k characters of each suffix, which are exactly the
4956
# pair (rank of the first k, rank of the next k). A second half that
5057
# runs past the end gets -1: ranks are never negative, so a shorter
51-
# suffix sorts before a longer one that shares its prefix.
58+
# suffix sorts before a longer one that shares its prefix. The index i
59+
# only breaks ties so the order stays deterministic; tied suffixes are
60+
# given the same rank in the renumbering below.
5261
keys = [(rank[i], rank[i + k] if i + k < n else -1, i) for i in range(n)]
5362
keys.sort()
5463
suffixes = [i for _, _, i in keys]
5564

5665
# Renumber so that equal 2k-prefixes share a rank and every distinct
5766
# prefix gets the next one. This keeps ranks dense in range(n).
67+
# `keys` is already in the same order as `suffixes`, so the first two
68+
# entries of neighbouring keys are the pairs to compare.
5869
new_rank = [0] * n
5970
for position in range(1, n):
6071
previous, current = suffixes[position - 1], suffixes[position]
61-
previous_key = (
62-
rank[previous],
63-
rank[previous + k] if previous + k < n else -1,
64-
)
65-
current_key = (
66-
rank[current],
67-
rank[current + k] if current + k < n else -1,
68-
)
69-
new_rank[current] = new_rank[previous] + int(previous_key != current_key)
72+
same_prefix = keys[position - 1][:2] == keys[position][:2]
73+
new_rank[current] = new_rank[previous] + int(not same_prefix)
7074

7175
rank = new_rank
7276
# Dense ranks ending at n - 1 means every suffix has a unique rank, so
@@ -77,3 +81,9 @@ def suffix_array(text: str) -> list[int]:
7781
k *= 2
7882

7983
return suffixes
84+
85+
86+
if __name__ == "__main__":
87+
import doctest
88+
89+
doctest.testmod()

0 commit comments

Comments
 (0)