

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I have implemented a solution by comparing the suffixes of a string after sorting the suffix list. Is there any linear time algorithm that performs better than this piece of code?

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
void preCompute(string input[],string s)
    int n = s.length();
        input[i] = s.substr(i,n);
string LongestCommonSubString(string first,string second)
    int n = min(first.length(),second.length());
            return first.substr(0,i);
    return first.substr(0,n);
string lrs(string s)
    int n = s.length();
    string input[n];
    sort(input, input+n);
    string lrs = "";
        string x = LongestCommonSubString(input[i],input[i+1]);
            lrs = x;
    return lrs;
int main()
    string input[2] = {"banana","missisipi"};
    return 0;

I found a really good resource for this question. See here

share|improve this question
up vote 5 down vote accepted

You can build a suffix tree in linear time (see this). The longest repeated substring corresponds to the deepest internal node (when I say deepest I mean the path from the root has the maximum number of characters, not the maximum number of edges). The reason for that is simple. Internal nodes correspond to prefixes of suffixes (ie substrings) that occur in multiple suffixes.

In reality, this is fairly complex. So the approach you are taking is good enough. I have a few modifications that I can suggest:

  1. Do not create substrings, substrings can be denoted by a pair of numbers. When you need the actual characters, look up the original string. In fact suffixes, correspond to a single index (the start index).

  2. The longest common prefix of every pair of consecutive suffixes, can be computed while constructing your suffix array in linear time (but O(n log n) algorithms are much easier). Consult the references of this.

  3. If you really insist on running the whole thing in linear time, then you can construct the suffix array in linear time. I am sure if you search around a bit, you can easily find pointers.

  4. There are very elegant (but not linear) implementations described here.

share|improve this answer

Your Answer


