class SuffixArray:
def __init__(self, text):
self.text = text
self.n = len(text)
# The Suffix Array: stores starting indices of sorted suffixes
self.sa = self._build_suffix_array()
# The LCP Array (Longest Common Prefix): stores lengths of common prefixes
# between adjacent suffixes in the sorted array. (Optional, but useful for advanced queries)
self.lcp = self._build_lcp_array()
def _build_suffix_array(self):
"""
Builds the Suffix Array using the Prefix Doubling algorithm.
Complexity: O(n log^2 n)
"""
n = self.n
k = 1
# Initial rank based on the character's ASCII value
# We store tuples: (rank[i], rank[i+k], index)
suffixes = []
for i in range(n):
# (rank_tuple, index)
# ord is used for initial character ranking
suffixes.append([(ord(self.text[i]) - ord('a'), 0), i])
# Update the second key for the first iteration
# If i+k is out of bounds, rank is -1 (to sort shorter strings first if prefixes match)
for i in range(n):
if i + k < n:
suffixes[i][0] = (suffixes[i][0][0], ord(self.text[i+k]) - ord('a'))
else:
suffixes[i][0] = (suffixes[i][0][0], -1)
# Sort initially
suffixes.sort(key=lambda x: x[0])
# Prefix Doubling Loop
while k < n:
# Re-assign ranks based on the previous sort
# rank_map maps the sorted tuple to a new compressed integer rank
new_rank = 0
prev_rank = suffixes[0][0]
suffixes[0][0] = (0, suffixes[0][0][1]) # First element gets rank 0
rank_mapping = {prev_rank: 0}
for i in range(1, n):
curr_tuple = suffixes[i][0]
if curr_tuple != prev_rank:
new_rank += 1
prev_rank = curr_rank
# Update the tuple to the new rank for the next iteration
# The first element becomes the combined rank of the previous two keys
suffixes[i][0] = (new_rank, 0) # Second part is 0 initially
# If all ranks are distinct (0 to n-1), we are done
if new_rank == n - 1:
break
# Update the 'second' key for the next sort
# Map index -> current rank
index_to_rank = [0] * n
for s in suffixes:
index = s[1]
current_rank = s[0][0]
index_to_rank[index] = current_rank
for i in range(n):
index = suffixes[i][1]
next_index = index + k
second_rank = 0
if next_index < n:
second_rank = index_to_rank[next_index]
suffixes[i][0] = (suffixes[i][0][0], second_rank)
k *= 2
suffixes.sort(key=lambda x: x[0])
# Extract just the indices
return [s[1] for s in suffixes]
def _build_lcp_array(self):
"""
Builds the LCP array using Kasai's Algorithm.
Complexity: O(n)
"""
n = self.n
sa = self.sa
lcp = [0] * n
# Inverse Suffix Array: rank[i] is the rank of the suffix starting at i
rank = [0] * n
for i in range(n):
rank[sa[i]] = i
k = 0
for i in range(n):
if rank[i] == n - 1:
k = 0
continue
j = sa[rank[i] + 1]
# Calculate match length
while i + k < n and j + k < n and self.text[i + k] == self.text[j + k]:
k += 1
lcp[rank[i]] = k
# Optimization: we know the next match is at least k-1
if k > 0:
k -= 1
return lcp
def search(self, pattern):
"""
Finds all occurrences of the pattern in the text.
Returns a list of starting indices.
Complexity: O(m log n)
"""
m = len(pattern)
l = 0
r = self.n
# Binary Search for Left Bound
while l < r:
mid = (l + r) // 2
# Compare pattern with suffix at sa[mid]
suffix_index = self.sa[mid]
substring = self.text[suffix_index : min(suffix_index + m, self.n)]
if pattern > substring:
l = mid + 1
else:
r = mid
start = l
# Binary Search for Right Bound
r = self.n
while l < r:
mid = (l + r) // 2
suffix_index = self.sa[mid]
substring = self.text[suffix_index : min(suffix_index + m, self.n)]
if pattern < substring:
r = mid
else:
l = mid + 1
end = l
# The matching suffixes are in the range [start, end) in the Suffix Array
if start == end:
return [] # No match
# Return the sorted indices
return sorted(self.sa[start:end])
# --- Usage Example ---
if __name__ == "__main__":
text = "banana"
pattern = "ana"
sa = SuffixArray(text)
print(f"Text: {text}")
print(f"Suffix Array: {sa.sa}")
# Expected SA for 'banana' is [5, 3, 1, 0, 4, 2]
# 5: a
# 3: ana
# 1: anana
# 0: banana
# 4: na
# 2: nana
matches = sa.search(pattern)
print(f"Pattern '{pattern}' found at indices: {matches}")