33https://cp-algorithms.com/string/suffix-array.html
44
55A 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
1214Time Complexity: O(n log² n) - where n is the length of the text
1315Space 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