跳到正文

算法·理论

Suffix Array

M1rai约 8 分钟
原文
文章信息与版本

文章信息

发布
2026年11月19日
收录
2026年11月20日
更新
2026年11月22日
篇幅
约 8 分钟

版本

  1. v2当前
  2. v1

You’re half a world away

But in my mind I whisper every single word you say


The Suffix Array (SA) is used to address the following problem:

You are given a string ss of length nn (0-indexed); sort all of the nn suffixes of ss, in lexicographically increasing order.

Output the answer as a permutation pp, where px=ip_x=i indicates that the suffix s[i⋯(n−1)]s[i\cdots (n-1)] is the (x+1)(x+1)-th smallest among all suffixes.

Brute Force

Extract all suffixes from ss and simply sort them. This takes O(n2log⁡n)\mathcal{O}(n^2\log n) time and O(n2)\mathcal{O}(n^2) space.

Optimization 1

We do not need the full information from the entire strings of all nn original suffixes.

For convenience, we are going to sort all cyclic shifts instead of the suffixes of ss, after appending a character with an ASCII value smaller than every character in the alphabet (e.g., .). It can be shown that the solution for our new problem is identical to the original one.

In the ii-th iteration, our goal is to sort all suffixes, but ignoring all characters except the first 2i2^i ones. For i=0i=0, we can sort them directly. For i>0i>0, we use the idea of binary lifting, utilizing the information from the (i−1)(i-1)-th iteration. Iterate from 11 to ⌈log⁡n⌉\lceil \log n \rceil; In this process, we have to maintain two arrays:

  • pp: The answer after ii iterations.
  • cc: The ID of equivalence cclass distinguished by the first 2i2^i characters of each suffix.

For example, when s=ababa.s=\text{ababa.}, at the beginning of iteration i=1i=1 (that is, sorted by the first 20=12^0=1 character of the suffixes):

  • p0=5(.ababa),c0=1p_0=5(\textbf{.}\text{ababa}),c_0=1;
  • p1=0(ababa.),c1=2p_1=0(\textbf{a}\text{baba.}),c_1=2;
  • p2=2(aba.ab),c2=2p_2=2(\textbf{a}\text{ba.ab}),c_2=2;
  • p3=4(a.abab),c3=2p_3=4(\textbf{a}\text{.abab}),c_3=2;
  • p4=1(baba.a),c4=3p_4=1(\textbf{b}\text{aba.a}),c_4=3;
  • p5=3(ba.aba),c5=3p_5=3(\textbf{b}\text{a.aba}),c_5=3;

To sort by the order of the characters in [0,2i)[0,2^i) is essentially the same as: sorting by the ordered pair ([0,2i−1),[2i−1,2i))([0,2^{i-1}),[2^{i-1},2^i)); that is, sorting pp by (cx,c(x+2i−1)mod  n)(c_x,c_{(x+2^{i-1})\mod n}), where xx is an element of pp. c(x+2i−1)mod  nc_{(x+2^{i-1})\mod n} corresponds to the rank of the characters in [2i−1,2i)[2^{i-1},2^i) of ss after xx cyclic shifts (which is why we want to sort the cyclic shifts rather than suffixes).

Since we have O(log⁡n)\mathcal{O}(\log n) iterations and need to sort the whole thing in O(nlog⁡n)\mathcal{O}(n\log n) time in each iteration, the total time complexity is O(nlog⁡2n)\mathcal{O}(n\log^2n), and it only costs O(n)\mathcal{O}(n) space.

Optimization 1.1

The range of cc is O(n)\mathcal{O}(n). Use counting sort twice: first sort by c(x+2i−1)mod  nc_{(x+2^{i-1})\mod n}, then sort by cxc_x. It works since counting sort is stable. This reduces the time complexity to O(nlog⁡n)\mathcal{O}(n\log n).

Optimization ??

There is a solution in linear time.

Implementation

A minor constant optimization: Notice that we don’t need to actually do the first sort in every iteration; just apply pj←(pj−2i−1)mod  np_j\leftarrow (p_j-2^{i-1})\mod n to the entire array pp.

C++
int n;

inline int f(int x,int i){
    x+=(1<<(i-1));
    if(x>=n)    x-=n;
    return x;
}

void solve(){
    string s;
    cin>>s,n = s.length(),s+='$',n++;
    vector<int> p(n),c(n);
    map<char,int> mp;
    for(char c:s)   mp[c]++;
    for(auto it=++mp.begin();it!=mp.end();it++) it->snd+=prev(it)->snd;
    for(int i=n-1;i>=0;i--)    p[--mp[s[i]]] = i;
    int id = 0;
    for(int l=0,r=0;l<n;l=r,id++){
        while(r<n && s[p[l]]==s[p[r]])    c[p[r++]] = id;
    }
    id++;
    for(int i=1;(1<<(i-1))<=n;i++){
        for(int &j:p){
            j-=1<<(i-1);
            if(j<0) j+=n;
        }
        vector<int> tp = p,cnt(id);
        for(int j:c)    cnt[j]++;
        for(int j=1;j<id;j++)   cnt[j]+=cnt[j-1];
        for(int j=n-1;j>=0;j--) p[--cnt[c[tp[j]]]] = tp[j];
        id = 0;
        auto tc = c;
        tc[p[0]] = 0;
        for(int j=1;j<n;j++){
            if(tc[p[j-1]]==tc[p[j]] && tc[f(p[j-1],i)]==tc[f(p[j],i)])  c[p[j]] = id;
            else    c[p[j]] = ++id;
        }
        id++;
    }
    p.erase(p.begin());
    for(int i:p)    cout<<i+1<<" ";
    cout<<"\n";
}

Author: Misaka16172

GenAI usage: only for grammar check.

原文