We need to create a suffix array for efficient pattern matching. The instruction is a bit vague: "Create a suffix array for efficient pattern matching." Possibly we need to implement a suffix array construction algorithm, and then use it for pattern matching? Could be a coding task: given a string, build its suffix array and then use binary search to find occurrences of a pattern. The user didn't specify input/output. Could be a request to explain or code. Since it's a chat, maybe they want an explanation of suffix arrays and how to use them for pattern matching. Or they want a code snippet. Typically, in competitive programming contexts, you'd implement suffix array with sorting of suffixes, perhaps using the O(n log n) algorithm with ranking pairs. Also, pattern matching using binary search on the suffix array to find the range of suffixes that start with the pattern. So I'll provide a detailed answer: what is a suffix array, construction, and pattern matching. I'll include pseudocode or Python code. I'll aim for clarity.
The user might expect a step-by-step explanation. Since it's a "create" task, maybe they want a code that builds a suffix array for a given string. But we need to be careful: The prompt is just one sentence. In many LLM interactions, the user might ask to "Create a suffix array for efficient pattern matching." It could be a request to generate a code snippet. So I'll respond with a description and then provide a Python implementation.
Better to provide a solution: define suffix array, construction using doubling method (Manber & Myers), and then use binary search for pattern matching. I'll also discuss time complexity.
Thus, my response will include:
Explanation of suffix array: sorted array of all suffixes of a string.
How to build: O(n log n) using ranking tuples.
How to search for pattern: binary search to find lower and upper bound, O(m log n).
Python code for building suffix array (with sorting of tuples, but careful about O(n log^2 n) vs O(n log n) using key sorting; we can implement the doubling method efficiently using sorting of pairs with counting sort, but for simplicity we can use Python's sort on tuples of integers, which is O(n log n) per iteration? Actually typical implementation: sort suffixes by first character, then by 2 characters, etc., each iteration sorting pairs (rank[i], rank[i+k]) using sort, total O(n log^2 n) because each sort is O(n log n) and we have log n iterations. But Python's Timsort is fast enough for moderate strings. However we can optimize by using key with lambda that returns (rank[i], rank[i+k] if i+k < n else -1) but that still sorts based on tuple. That's O(n log n) per iteration. Since n up to maybe 10^5, O(n log^2 n) is okay. But there is a better O(n log n) using counting sort, but more complex. I'll present the simpler method.
Provide code for building suffix array, then pattern matching function.
Example usage.
I'll also discuss LCP array (optional) for faster matching, but not required.
Now write the answer.
I'll structure:
Definition
Construction algorithm (doubling)
Pattern matching using binary search
Implementation in Python
Complexity analysis
Example
Let's produce final response.
Suffix Array for Efficient Pattern Matching
A suffix array is a sorted array of all suffixes of a given string. It enables fast pattern matching (substrings) using binary search, achieving O(m log n) time per query (where m = pattern length, n = text length). It also serves as a space-efficient alternative to suffix trees.
Below I explain the construction of a suffix array using the doubling method (Manber–Myers algorithm) and how to perform pattern matching with it. A complete Python implementation is provided.
1. Building the Suffix Array
Given a string s of length n, we generate an array sa where sa[i] is the starting index of the i‑th lexicographically smallest suffix.
The doubling method works as follows:
Initially sort suffixes by their first character. Assign a rank to each suffix (its order in that sorting).
For step length k = 1, 2, 4, 8, … while k < n:
Sort suffixes using the pair (rank[i], rank[i+k]) where rank[i] is the current rank of the suffix starting at i, and rank[i+k] is the rank of the suffix starting k positions ahead (or -1 if out of bounds).
After sorting, assign new ranks. If two adjacent suffixes have the same pair, they get the same rank.
At the end, the order of suffixes is fully determined. The array of starting indices in that order is the suffix array.
Complexity: O(n log n) using comparison sorts, but practically O(n log² n) with Python's Timsort. For n up to 10⁵ it is fast enough.
2. Pattern Matching with Suffix Array
Once the suffix array is built, we can find all occurrences of a pattern p as follows:
Perform a binary search on the suffix array to find the first suffix that is lexicographically ≥ p.
Perform another binary search to find the last suffix that starts with p (i.e., suffix ≤ p + 'z'*...).
The suffixes between those indices are all the starting positions where p occurs.
Comparisons are done by comparing the substring of s starting at the suffix index with p. To avoid O(m) per comparison, we can compare character by character; in practice this still yields O(m log n) time.
3. Python Implementation
python
def build_suffix_array(s: str) -> list[int]:
"""Return suffix array of string s using doubling method."""
n = len(s)
# initial rank = character code (or order)
# we use tuple (rank[i], rank[i+k]) for sorting
# we maintain an array 'rank' of current ranks, and an array 'sa' of indices
k = 1
# initial sa = indices sorted by character (using ord)
sa = sorted(range(n), key=lambda i: s[i])
# rank[i] = rank of suffix starting at i
rank = [0] * n
r = 0
rank[sa[0]] = r
for i in range(1, n):
if s[sa[i]] != s[sa[i-1]]:
r += 1
rank[sa[i]] = r
tmp = [0] * n
while k < n:
# sort by (rank[i], rank[i+k]) using Python's sort with key
sa.sort(key=lambda i: (rank[i], rank[i+k] if i+k < n else -1))
tmp[sa[0]] = 0
for i in range(1, n):
prev, cur = sa[i-1], sa[i]
prev_key = (rank[prev], rank[prev+k] if prev+k < n else -1)
cur_key = (rank[cur], rank[cur+k] if cur+k < n else -1)
tmp[cur] = tmp[prev] + (prev_key != cur_key)
rank, tmp = tmp, rank # copy new ranks
k <<= 1
return sa
def pattern_matching(sa: list[int], s: str, p: str) -> list[int]:
"""Return all starting indices of pattern p in text s using suffix array."""
n = len(s)
m = len(p)
if m == 0:
return list(range(n+1))
# binary search for left bound
lo, hi = 0, n-1
left = n
while lo <= hi:
mid = (lo + hi) // 2
# compare s[sa[mid]:sa[mid]+m] with p
idx = sa[mid]
substr = s[idx:idx+m]
if substr >= p:
left = mid
hi = mid - 1
else:
lo = mid + 1
# binary search for right bound
lo, hi = 0, n-1
right = -1
while lo <= hi:
mid = (lo + hi) // 2
idx = sa[mid]
substr = s[idx:idx+m]
if substr <= p:
right = mid
lo = mid + 1
else:
hi = mid - 1
if left > right:
return []
return sorted(sa[left:right+1]) # indices may not be sorted; we sort them
The suffix array for "banana" is typically [5, 3, 1, 0, 4, 2] (corresponding to suffixes: "a", "ana", "anana", "banana", "na", "nana"). Pattern "ana" appears at positions 1 and 3.
4. Complexity
Construction: O(n log n) comparisons, each sort O(n log n) → O(n log² n) in practice, but still efficient for strings up to several hundred thousand characters.
Pattern matching: O(m log n) time per pattern, where m is pattern length, plus O(k) to output the k occurrences (if we sort the indices at the end, O(k log k)). In many implementations we can return the indices in the order they appear in the suffix array (they are already sorted by suffix, not by position). If you need them in increasing order, a final sort of the slice O(k log k) can be added.
5. Extensions
The LCP (Longest Common Prefix) array can be built from the suffix array in O(n) and allows pattern matching in O(m + log n) time (by using binary search with LCP information). It also enables advanced string processing tasks.
For huge strings, a linear-time construction algorithm (e.g., SA‑IS) can be used, but it is more complex.
This implementation provides a good balance between simplicity and efficiency for most competitive programming or educational purposes.