Suffix Array | Set 1 (Introduction)
Last Updated :
15 Mar, 2023
We strongly recommend to read following post on suffix trees as a pre-requisite for this post.
Pattern Searching | Set 8 (Suffix Tree Introduction)
A suffix array is a sorted array of all suffixes of a given string. The definition is similar to Suffix Tree which is compressed trie of all suffixes of the given text. Any suffix tree based algorithm can be replaced with an algorithm that uses a suffix array enhanced with additional information and solves the same problem in the same time complexity (Source Wiki).
A suffix array can be constructed from Suffix tree by doing a DFS traversal of the suffix tree. In fact Suffix array and suffix tree both can be constructed from each other in linear time.
Advantages of suffix arrays over suffix trees include improved space requirements, simpler linear time construction algorithms (e.g., compared to Ukkonen’s algorithm) and improved cache locality (Source: Wiki)
Example:
Let the given string be "banana".
0 banana 5 a
1 anana Sort the Suffixes 3 ana
2 nana ----------------> 1 anana
3 ana alphabetically 0 banana
4 na 4 na
5 a 2 nana
So the suffix array for "banana" is {5, 3, 1, 0, 4, 2}
Naive method to build Suffix Array
A simple method to construct suffix array is to make an array of all suffixes and then sort the array. Following is implementation of simple method.
CPP
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
struct suffix
{
int index;
char *suff;
};
int cmp( struct suffix a, struct suffix b)
{
return strcmp (a.suff, b.suff) < 0? 1 : 0;
}
int *buildSuffixArray( char *txt, int n)
{
struct suffix suffixes[n];
for ( int i = 0; i < n; i++)
{
suffixes[i].index = i;
suffixes[i].suff = (txt+i);
}
sort(suffixes, suffixes+n, cmp);
int *suffixArr = new int [n];
for ( int i = 0; i < n; i++)
suffixArr[i] = suffixes[i].index;
return suffixArr;
}
void printArr( int arr[], int n)
{
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
cout << endl;
}
int main()
{
char txt[] = "banana" ;
int n = strlen (txt);
int *suffixArr = buildSuffixArray(txt, n);
cout << "Following is suffix array for " << txt << endl;
printArr(suffixArr, n);
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.Arrays;
class suffix_array {
public static void main(String[] args) throws Exception
{
String word = "banana" ;
String arr1[] = new String[word.length()];
String arr2[] = new String[word.length()];
ArrayList<Integer> suffix_index
= new ArrayList<Integer>();
int suffix_array[] = new int [word.length()];
for ( int i = 0 ; i < word.length(); i++) {
arr1[i] = word.substring(i);
}
arr2 = arr1.clone();
Arrays.sort(arr1);
for (String i : arr1) {
String piece = i;
int index
= new suffix_array().index(arr2, piece);
suffix_index.add(index);
}
for ( int i = 0 ; i < suffix_array.length; i++) {
suffix_array[i] = suffix_index.get(i);
}
System.out.println(
"following is the suffix array for banana" );
for ( int i : suffix_array) {
System.out.print(i + " " );
}
}
int index(String arr[], String item)
{
for ( int i = 0 ; i < arr.length; i++) {
if (item == arr[i])
return i;
}
return - 1 ;
}
}
|
Python3
import sys
class Suffix:
def __init__( self , index, suff):
self .index = index
self .suff = suff
def cmp (a, b):
return (a.suff < b.suff) - (a.suff > b.suff)
def build_suffix_array(txt, n):
suffixes = [Suffix(i, txt[i:]) for i in range (n)]
suffixes.sort(key = cmp )
suffix_arr = [suffixes[i].index for i in range (n)]
return suffix_arr
def print_arr(arr):
for i in range ( len (arr)):
print (arr[i], end = " " )
print ()
def main():
txt = "banana"
n = len (txt)
suffix_arr = build_suffix_array(txt, n)
print ( "Following is suffix array for" , txt)
print_arr(suffix_arr)
if __name__ = = "__main__" :
main()
|
C#
using System;
using System.Linq;
class SuffixArray
{
private readonly string _text;
private readonly int [] _suffixArray;
private struct Suffix
{
public int Index { get ; set ; }
public string Suff { get ; set ; }
}
private static int CompareSuffixes(Suffix a, Suffix b)
{
return string .Compare(a.Suff, b.Suff, StringComparison.Ordinal);
}
public SuffixArray( string text)
{
_text = text;
var n = _text.Length;
var suffixes = new Suffix[n];
for ( var i = 0; i < n; i++)
{
suffixes[i] = new Suffix
{
Index = i,
Suff = _text.Substring(i)
};
}
Array.Sort(suffixes, CompareSuffixes);
_suffixArray = new int [n];
for ( var i = 0; i < n; i++)
{
_suffixArray[i] = suffixes[i].Index;
}
}
public int [] GetSuffixArray()
{
return _suffixArray;
}
}
class Program
{
static void Main( string [] args)
{
var txt = "banana" ;
var suffixArray = new SuffixArray(txt);
Console.WriteLine( "Following is suffix array for " + txt);
Console.WriteLine( string .Join( " " , suffixArray.GetSuffixArray().Select(x => x.ToString())));
}
}
|
Javascript
function comp(a, b) {
const name1 = a.suff;
const name2 = b.suff;
let comparison = 0;
if (name1 > name2) {
comparison = 1;
} else if (name1 < name2) {
comparison = -1;
}
return comparison;
}
function buildSuffixArray(txt, n) {
var suffixes = [];
for ( var i = 0; i < n; i++) {
var suffix = {};
suffix.index = i;
suffix.suff = txt.substr(i);
suffixes.push(suffix);
}
suffixes.sort(comp);
var suffixArr = [];
for ( var i = 0; i < n; i++) suffixArr[i] = suffixes[i].index;
return suffixArr;
}
function printArr(arr, n) {
for ( var i = 0; i < n; i++) {
console.log(arr[i]);
}
}
var txt = "banana" ;
var n = txt.length;
var suffixArr = buildSuffixArray(txt, n);
console.log( "Following is suffix array for " + txt);
printArr(suffixArr, n);
|
Output
Following is suffix array for banana
5 3 1 0 4 2
Time Complexity: O(n*k*Logn). if we consider a O(nLogn)) algorithm used for sorting. The sorting step itself takes O(n*k*Logn) time as every comparison is a comparison of two strings and the comparison takes O(K) time where K is max length of string in given array.
Auxiliary Space: O(n)
There are many efficient algorithms to build suffix array. We will soon be covering them as separate posts.
Search a pattern using the built Suffix Array
To search a pattern in a text, we preprocess the text and build a suffix array of the text. Since we have a sorted array of all suffixes, Binary Search can be used to search. Following is the search function. Note that the function doesn’t report all occurrences of pattern, it only report one of them.
CPP
void search( char *pat, char *txt, int *suffArr, int n)
{
int m = strlen (pat);
int l = 0, r = n-1;
while (l <= r)
{
int mid = l + (r - l)/2;
int res = strncmp (pat, txt+suffArr[mid], m);
if (res == 0)
{
cout << "Pattern found at index " << suffArr[mid];
return ;
}
if (res < 0) r = mid - 1;
else l = mid + 1;
}
cout << "Pattern not found" ;
}
int main()
{
char txt[] = "banana" ;
char pat[] = "nan" ;
int n = strlen (txt);
int *suffArr = buildSuffixArray(txt, n);
search(pat, txt, suffArr, n);
return 0;
}
|
Python3
import sys
def search(pat, txt, suffArr, n):
m = len (pat)
l = 0
r = n - 1
while l < = r:
mid = l + (r - l) / / 2
res = txt[suffArr[mid]:suffArr[mid] + m]
if res = = pat:
print ( "Pattern found at index" , suffArr[mid])
return
if res < pat:
l = mid + 1
else :
r = mid - 1
print ( "Pattern not found" )
def buildSuffixArray(txt, n):
suffixes = [txt[i:] for i in range (n)]
suffixes.sort()
suffArr = [txt.index(suffix) for suffix in suffixes]
return suffArr
def main():
txt = "banana"
pat = "nan"
n = len (txt)
suffArr = buildSuffixArray(txt, n)
search(pat, txt, suffArr, n)
return 0
if __name__ = = '__main__' :
sys.exit(main())
|
Javascript
function search(pat, txt, suffArr, n) {
var m = pat.length;
var l = 0;
var r = n - 1;
while (l <= r) {
var mid = l + Math.floor((r - l) / 2);
var c = txt.substring(suffArr[mid]);
var res = 0;
for ( var i = 0; i < m; i++) {
if (pat[i] == c[i]) {
continue ;
} else if (pat[i] < c[i]) {
res = -1;
break ;
} else {
res = 1;
break ;
}
}
if (res == 0) {
console.log( "Pattern found at index " + suffArr[mid]);
return ;
}
if (res < 0) r = mid - 1;
else l = mid + 1;
}
console.log( "Pattern not found" );
}
function comp(a, b) {
const name1 = a.suff;
const name2 = b.suff;
let comparison = 0;
if (name1 > name2) {
comparison = 1;
} else if (name1 < name2) {
comparison = -1;
}
return comparison;
}
function buildSuffixArray(txt, n) {
var suffixes = [];
for ( var i = 0; i < n; i++) {
var suffix = {};
suffix.index = i;
suffix.suff = txt.substr(i);
suffixes.push(suffix);
}
suffixes.sort(comp);
var suffixArr = [];
for ( var i = 0; i < n; i++) suffixArr[i] = suffixes[i].index;
return suffixArr;
}
var txt = "banana" ;
var pat = "nan" ;
var n = txt.length;
var suffArr = buildSuffixArray(txt, n);
search(pat, txt, suffArr, n);
|
Java
import java.io.*;
public class GFG {
static void search(String pat, String txt, int [] suffArr, int n)
{
int m = pat.length();
int l = 0 ;
int r = n - 1 ;
while (l <= r) {
int mid = l + (r - l) / 2 ;
String res = txt.substring(suffArr[mid], suffArr[mid] + m);
if (res.equals(pat)) {
System.out.println( "Pattern found at index " + suffArr[mid]);
return ;
}
if (res.compareTo(pat) < 0 ) {
l = mid + 1 ;
} else {
r = mid - 1 ;
}
}
System.out.println( "Pattern not found" );
}
static int [] buildSuffixArray(String txt, int n)
{
String[] suffixes = new String[n];
for ( int i = 0 ; i < n; i++) {
suffixes[i] = txt.substring(i, n);
}
java.util.Arrays.sort(suffixes);
int [] suffArr = new int [n];
for ( int i = 0 ; i < n; i++) {
suffArr[i] = txt.indexOf(suffixes[i]);
}
return suffArr;
}
public static void main(String[] args)
{
String txt = "banana" ;
String pat = "nan" ;
int n = txt.length();
int [] suffArr = buildSuffixArray(txt, n);
search(pat, txt, suffArr, n);
}
}
|
C#
using System;
class GFG {
static void Search( string pat, string txt,
int [] suffArr, int n)
{
int m = pat.Length;
int l = 0;
int r = n - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
string res = txt.Substring(suffArr[mid], m);
if (res.Equals(pat)) {
Console.WriteLine( "Pattern found at index "
+ suffArr[mid]);
return ;
}
if (res.CompareTo(pat) < 0) {
l = mid + 1;
}
else {
r = mid - 1;
}
}
Console.WriteLine( "Pattern not found" );
}
static int [] BuildSuffixArray( string txt, int n)
{
string [] suffixes = new string [n];
for ( int i = 0; i < n; i++) {
suffixes[i] = txt.Substring(i, n - i);
}
Array.Sort(suffixes);
int [] suffArr = new int [n];
for ( int i = 0; i < n; i++) {
suffArr[i] = txt.IndexOf(suffixes[i]);
}
return suffArr;
}
static void Main( string [] args)
{
string txt = "banana" ;
string pat
= "nan" ;
int n = txt.Length;
int [] suffArr = BuildSuffixArray(txt, n);
Search(pat, txt, suffArr, n);
}
}
|
Output:
Pattern found at index 2
Time Complexity: O(mlogn)
Auxiliary Space: O(m+n)
There are more efficient algorithms to search pattern once the suffix array is built. In fact there is a O(m) suffix array based algorithm to search a pattern. We will soon be discussing efficient algorithm for search.
Applications of Suffix Array
Suffix array is an extremely useful data structure, it can be used for a wide range of problems. Following are some famous problems where Suffix array can be used.
1) Pattern Searching
2) Finding the longest repeated substring
3) Finding the longest common substring
4) Finding the longest palindrome in a string
See this for more problems where Suffix arrays can be used.
This post is a simple introduction. There is a lot to cover in Suffix arrays. We have discussed a O(nLogn) algorithm for Suffix Array construction here. We will soon be discussing more efficient suffix array algorithms.
References:
http://www.stanford.edu/class/cs97si/suffix-array.pdf
http://en.wikipedia.org/wiki/Suffix_array
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...