Lexicographical Maximum substring of string

Given a string s we have to find the lexicographical maximum substring of a string


Input : s = "ababaa"
Output : babaa
Explanation : "babaa" is the maximum lexicographic susbtring formed from this string

Input : s = "asdfaa"
Output : sdfaa

The idea is simple, we traverse through all substrings. For every substring, we compare it with current result and update result if needed.

[sourcecode language=”CPP”]
// CPP program to find the lexicographically
// maximum substring.
#include <bits/stdc++.h>
using namespace std;

string LexicographicalMaxString(string str)
// loop to find the max leicographic
// substring in the substring array
string mx = "";
for (int i = 0; i < str.length(); ++i)
mx = max(mx, str.substr(i));

return mx;

int main()
string str = "ababaa";
cout << LexicographicalMaxString(str);
return 0;



Time Complexity : O(n)
Space Complexity : O(n)

Optimization :
We find largest character and all its indexes. Now we simply traverse through all instances of the largest character to find lexicographically maximum substring.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : 29AjayKumar, Sanjit_Prasad

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.