Lexicographical Maximum substring of string - GeeksforGeeks

28 Feb, 2022
Given a string s we have to find the lexicographical maximum substring of a string
Examples: 
Input : s = "ababaa"
Output : babaa
Explanation : "babaa" is the maximum lexicographic substring 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 the current result and update the result if needed.
Below is the implementation:
C++
Java
Python3
C#
Javascript
// CPP program to find the lexicographically// maximum substring.#include <bits/stdc++.h>using namespace std; string LexicographicalMaxString(string str){    // loop to find the max lexicographic    // substring in the substring array    string mx = "";    for (int i = 0; i < str.length(); ++i)        mx = max(mx, str.substr(i));     return mx;} // Driver codeint main(){    string str = "ababaa";    cout << LexicographicalMaxString(str);    return 0;}
// Java program to find the lexicographically// maximum substring. class GFG {     static String LexicographicalMaxString(String str)    {        // loop to find the max lexicographic        // substring in the substring array        String mx = "";        for (int i = 0; i < str.length(); ++i) {            if (mx.compareTo(str.substring(i)) <= 0) {                mx = str.substring(i);            }        }         return mx;    }     // Driver code    public static void main(String[] args)    {        String str = "ababaa";        System.out.println(LexicographicalMaxString(str));    }}// This code is contributed by 29AjayKumar
# Python 3 program to find the# lexicographically maximum substring.def LexicographicalMaxString(str):         # loop to find the max lexicographic    # substring in the substring array    mx = ""    for i in range(len(str)):        mx = max(mx, str[i:])     return mx # Driver codeif __name__ == '__main__':    str = "ababaa"    print(LexicographicalMaxString(str))     # This code is contributed by# Sanjit_Prasad
// C# program to find the lexicographically// maximum substring. using System;public class GFG {     static String LexicographicalMaxString(String str)    {        // loop to find the max lexicographic        // substring in the substring array        String mx = "";        for (int i = 0; i < str.Length; ++i) {            if (mx.CompareTo(str.Substring(i)) <= 0) {                mx = str.Substring(i);            }        }         return mx;    }     // Driver code    public static void Main()    {        String str = "ababaa";        Console.WriteLine(LexicographicalMaxString(str));    }} // This code is contributed by 29AjayKumar
<script> // JavaScript program to find the lexicographically// maximum substring.   function LexicographicalMaxString(str)    {        // loop to find the max lexicographic    // substring in the substring array    var mx = "";    for (var i = 0; i < str.length; ++i) {        if (mx.localeCompare(str.substring(i)) <= 0) {            mx = str.substring(i);        }    }     return mx;} // Driver code   var str = "ababaa";   document.write(LexicographicalMaxString(str)); // This code is contributed by 29AjayKumar </script>
babaa
 
Optimization : We find the largest character and all its indexes. Now we simply traverse through all instances of the largest character to find lexicographically maximum substring.
Here we follow the above approach. 
C++
Java
Python3
C#
Javascript
// C++ program to find the lexicographically// maximum substring.#include <bits/stdc++.h>using namespace std; string LexicographicalMaxString(string str){    char maxchar = 'a';    vector<int> index;     // We store all the indexes of maximum    // characters we have in the string    for (int i = 0; i < str.length(); i++) {        if (str[i] >= maxchar) {            maxchar = str[i];            index.push_back(i);        }    }    string maxstring = "";     // We form a substring from that maximum    // character index till end and check if    // its greater that maxstring    for (int i = 0; i < index.size(); i++) {        if (str.substr(index[i], str.length()) > maxstring) {            maxstring = str.substr(index[i], str.length());        }    }    return maxstring;} // Driver codeint main(){    string str = "acbacbc";    cout << LexicographicalMaxString(str);    return 0;}
// Java program to find the lexicographically// maximum substring.import java.io.*;import java.util.*;class GFG{     static String LexicographicalMaxString(String str)  {    char maxchar = 'a';    ArrayList<Integer> index = new ArrayList<Integer>();     // We store all the indexes of maximum    // characters we have in the string    for (int i = 0; i < str.length(); i++)    {      if (str.charAt(i) >= maxchar)      {        maxchar = str.charAt(i);        index.add(i);      }    }    String maxstring = "";     // We form a substring from that maximum    // character index till end and check if    // its greater that maxstring    for (int i = 0; i < index.size(); i++)    {      if (str.substring(index.get(i),                        str.length()).compareTo( maxstring) > 0)      {        maxstring = str.substring(index.get(i),                                  str.length());      }    }    return maxstring;  }   // Driver code  public static void main (String[] args)  {       String str = "acbacbc";      System.out.println(LexicographicalMaxString(str));  }} // This code is contributed by rag2127.
# Python 3 program to find# the lexicographically# maximum substring.def LexicographicalMaxString(st):     maxchar = 'a'    index = []     # We store all the indexes    # of maximum characters we    # have in the string    for i in range(len(st)):        if (st[i] >= maxchar):            maxchar = st[i]            index.append(i)     maxstring = ""     # We form a substring from that    # maximum character index till    # end and check if its greater    # that maxstring    for i in range(len(index)):        if (st[index[i]: len(st)] >            maxstring):            maxstring = st[index[i]:                        len(st)]    return maxstring # Driver codeif __name__ == "__main__":     st = "acbacbc"    print(LexicographicalMaxString(st)) # This code is contributed by Chitranayal
// C# program to find the lexicographically// maximum substring.using System;using System.Collections.Generic; class GFG{     static string LexicographicalMaxString(string str){    char maxchar = 'a';    List<int> index = new List<int>();         // We store all the indexes of maximum    // characters we have in the string    for(int i = 0; i < str.Length; i++)    {        if (str[i] >= maxchar)        {            maxchar = str[i];            index.Add(i);        }    }    string maxstring = "";         // We form a substring from that maximum    // character index till end and check if    // its greater that maxstring    for(int i = 0; i < index.Count; i++)    {        if (str.Substring(index[i]).CompareTo(maxstring) > 0)        {            maxstring = str.Substring(index[i]);        }    }    return maxstring;} // Driver codestatic public void Main(){    string str = "acbacbc";         Console.Write(LexicographicalMaxString(str));}} // This code is contributed by avanitrachhadiya2155
<script>// Javascript program to find the lexicographically// maximum substring. function LexicographicalMaxString(str){    let maxchar = 'a';    let index = [];         // We store all the indexes of maximum    // characters we have in the string    for (let i = 0; i < str.length; i++)    {      if (str[i] >= maxchar)      {        maxchar = str[i];        index.push(i);      }    }    let maxstring = "";      // We form a substring from that maximum    // character index till end and check if    // its greater that maxstring    for (let i = 0; i < index.length; i++)    {      if (str.substring(index[i],                        str.length) > maxstring)      {        maxstring = str.substring(index[i],                                  str.length);      }    }    return maxstring;} // Driver codelet str = "acbacbc"; document.write(LexicographicalMaxString(str)); // This code is contributed by ab2127</script>
cbc
 
YouTubeGeeksforGeeks500K subscribersLexicographical Maximum substring of string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:51•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=pMS4P7wxTU8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
29AjayKumar
Sanjit_Prasad
prajmsidc
qbert
ukasp
rag2127
avanitrachhadiya2155
ab2127
varshagumber28
sumitgumber28
cpp-string
lexicographic-ordering
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack
Different methods to reverse a string in C/C++
KMP Algorithm for Pattern Searching
Convert string to char array in C++
Array of Strings in C++ (5 Different Ways to Create)
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Reverse words in a given string
Check whether two strings are anagram of each other