Algorithm:-
s --> given string whose suffix strings are to be sorted (let s = 'ababba')
add a special symbol '$' at end of 's', '$' is smallest character. (s = 'ababba$'
Represent all suffix strings by integers representing the beginning index of suffix string. (suffixStrings = [6, 5, 4, 3, 2, 1, 0])
Then, compare 1st character of all suffixes, and partition them based on their 1st character. (Partitions = [(6), (0, 2, 5), (4, 3, 1)], representing --> [('$'), ('ababba$', 'abba$', 'a$'), ('ba$', 'bba$', 'babba$')]
if any partition containes a single string, print it, since it is smallest string among remaining suffixes
Partition the remaing partitions based on 2nd character.
Continue this process 3rd, 4th and so on characters, until all partitions remain with only one string.
Here is the code.
#include <bits/stdc++.h>
using namespace std;
void sortSuffixes(vector<int> &suffixStrings, int c, const string &s)
{
vector< vector<int> > temp;
int n = suffixStrings.size(); //O(1)
map<char, vector<int> > mmap;
for(int i=0;i<n;i++) // O(n)
{
mmap[s[suffixStrings[i] + c]].push_back(suffixStrings[i]);
}
map<char, vector<int> > :: iterator it = mmap.begin();
while(it != mmap.end())
{
if((it->second).size() == 1)
{
cout << (it->second)[0]<<" ";
}
else
{
sortSuffixes(it->second, c+1, s);
}
it++;
}
}
int main()
{
string s;
cin>>s;
s = s + '$';
vector<int> suffixStrings;
int n = s.length();
for(int i = n-1; i >= 0; i--) // O(n)
{
suffixStrings.push_back(i);
}
sortSuffixes(suffixStrings, 0, s);
return 0;
}
How to calculate it's time complexity? I feel it's O(length of given string)