Get the best out of our app
GeeksforGeeks App
Open App
Browser
Continue

# Longest string in non-decreasing order of ASCII code and in arithmetic progression

Given a non-empty string S of uppercase alphabets of length L and the task is to find the longest string from the given string with characters arranged in descending order of their ASCII code and in arithmetic progression such that the common difference should be as low as possible and the characters of the string to be of higher ASCII value.

Note: The string contains minimum three different characters.

Examples

Input : S = “ABCPQR”
Output : “RQP”
Two strings of maximum length are possible – “CBA” and “RPQ”. But since the string should be of higher ASCII value hence, the output is “RPQ”.

Input : S = “ADGJPRT”
Output : “JGDA”

Approach:

The maximum possible common difference for minimum 3 characters to be in arithmetic progression is 12. Hence, precompute all characters that are present in the string using a hashmap and then iterate from the character having maximum ASCII value i.e. ‘Z’ to the character having minimum ASCII value i.e. ‘A’. If the current character exists in the given string, consider it as the starting character of the arithmetic progression sequence and iterate again over all possible common differences i.e. from 1 to 12.

check for every current common difference that if the character exists in the given string, increment the current length of the longest required string. Now, there exist two cases when maximum length ans minimum common difference needs to be updated.

1. When the current length is more than the maximum length.
2. When the current length is equal to the maximum length and current common difference is less than the minimum common difference, then common difference needs to be updated.

Also, at every updation of these two parameters, starting character of the string or arithmetic progression sequence must also be updated.

Below is the implementation of above approach:

## C++

 // C++ Program to find the longest string// with characters arranged in non-decreasing// order of ASCII and in arithmetic progression#include using namespace std; // Function to find the longest Stringstring findLongestString(string S){    // Stores the maximum length of required string    int maxLen = 0;     // Stores the optimal starting character of    // required string or arithmetic progression sequence    int bestStartChar;     // Stores the optimal i.e. minimum common difference    // of required string    int minCommonDifference = INT_MAX;     unordered_map mp;    for (int i = 0; i < S.size(); i++)        mp[S[i]] = true;     // Iterate over the loop in non decreasing order    for (int startChar = 'Z'; startChar > 'A'; startChar--) {         // Process further only if current character        // exists in the given string        if (mp[startChar]) {             // Iterate over all possible common differences            // of AP sequence and update maxLen accordingly            for (int currDiff = 1; currDiff <= 12; currDiff++) {                int currLen = 1;                 // Iterate over the characters at any interval                // of current common difference                for (int ch = startChar - currDiff; ch >= 'A';                     ch -= currDiff) {                    if (mp[ch])                        currLen++;                    else                        break;                }                 // Update maxLen and other parameters if the currLen                // is greater than maxLen or if the current                // difference is smaller than minCommonDifference                if (currLen > maxLen || (currLen == maxLen                                         && currDiff < minCommonDifference)) {                    minCommonDifference = currDiff;                    maxLen = currLen;                    bestStartChar = startChar;                }            }        }    }    string longestString = "";     // Store the string in decreasing order of    // arithmetic progression    for (int i = bestStartChar;         i >= (bestStartChar - (maxLen - 1) * minCommonDifference);         i -= minCommonDifference)        longestString += char(i);     return longestString;} // Driver Codeint main(){    string S = "ADGJPRT";    cout << findLongestString(S) << endl;    return 0;}

## Java

 // Java Program to find the longest string// with characters arranged in non-decreasing// order of ASCII and in arithmetic progressionimport java.util.*;import java.lang.*;  public class GFG {    // Function to find the longest String    static String findLongestString(String S)    {        // Stores the maximum length of required string        int maxLen = 0;             // Stores the optimal starting character of        // required string or arithmetic progression sequence        int bestStartChar = 0;             // Stores the optimal i.e. minimum common difference        // of required string        int minCommonDifference = Integer.MAX_VALUE;             HashMap hm = new HashMap                                ();        for (int i = 0; i < S.length(); i++)            hm.put(S.charAt(i), true);             // Iterate over the loop in non decreasing order        for (int startChar = 'Z'; startChar > 'A'; startChar--) {                 // Process further only if current character            // exists in the given string            if (hm.containsKey((char)startChar)) {                     // Iterate over all possible common differences                // of AP sequence and update maxLen accordingly                for (int currDiff = 1; currDiff <= 12; currDiff++) {                    int currLen = 1;                         // Iterate over the characters at any interval                    // of current common difference                    for (int ch = startChar - currDiff; ch >= 'A';                        ch -= currDiff) {                        if (hm.containsKey((char)ch))                            currLen++;                        else                            break;                    }                         // Update maxLen and other parameters if the currLen                    // is greater than maxLen or if the current                    // difference is smaller than minCommonDifference                    if (currLen > maxLen || (currLen == maxLen                                 && currDiff < minCommonDifference)) {                        minCommonDifference = currDiff;                        maxLen = currLen;                        bestStartChar = startChar;                    }                }            }        }        String longestString = "";             // Store the string in decreasing order of        // arithmetic progression        char ch;        for (int i = bestStartChar;         i >= (bestStartChar - (maxLen - 1) * minCommonDifference);         i -= minCommonDifference)        {            ch = (char)i;            longestString += ch;        }        return longestString;    }      // Driver Code    public static void main(String args[])    {        String S = "ADGJPRT";        System.out.println(findLongestString(S));    }}// This code is contributed by Nishant Tanwar

## Python3

 # Python 3 Program to find the longest string# with characters arranged in non-decreasing# order of ASCII and in arithmetic progressionimport sys # Function to find the longest Stringdef findLongestString(S):     # Stores the maximum length of required string    maxLen = 0     # Stores the optimal starting character of    # required string or arithmetic progression sequence    bestStartChar = 0     # Stores the optimal i.e. minimum common difference    # of required string    minCommonDifference = sys.maxsize     mp = {}    for i in range(len(S)):        mp[S[i]] = True     # Iterate over the loop in non decreasing order    for startChar in range(ord('Z'), ord('A'), -1):         # Process further only if current character        # exists in the given string        if chr(startChar) in mp:             # Iterate over all possible common differences            # of AP sequence and update maxLen accordingly            for currDiff in range(1, 13):                currLen = 1                 # Iterate over the characters at any interval                # of current common difference                for ch in range(startChar - currDiff, ord('A') - 1, -currDiff):                    if (chr(ch) in mp):                        currLen += 1                     else:                        break                 # Update maxLen and other parameters if the currLen                # is greater than maxLen or if the current                # difference is smaller than minCommonDifference                if (currLen > maxLen or (currLen == maxLen                                         and currDiff < minCommonDifference)):                    minCommonDifference = currDiff                    maxLen = currLen                    bestStartChar = startChar     longestString = ""     # Store the string in decreasing order of    # arithmetic progression    for i in range(bestStartChar,                   (bestStartChar - (maxLen - 1) * minCommonDifference)-1, -minCommonDifference):        longestString += chr(i)     return longestString # Driver Codeif __name__ == "__main__":     S = "ADGJPRT"    print(findLongestString(S))     # This code is contributed by ukasp.

## C#

 // C# Program to find the longest string// with characters arranged in non-decreasing// order of ASCII and in arithmetic progression using System;using System.Collections ; public class GFG {    // Function to find the longest String    static String findLongestString(String S)    {        // Stores the maximum length of required string        int maxLen = 0;             // Stores the optimal starting character of        // required string or arithmetic progression sequence        int bestStartChar = 0;             // Stores the optimal i.e. minimum common difference        // of required string        int minCommonDifference = Int32.MaxValue ;             Hashtable hm = new Hashtable ();        for (int i = 0; i < S.Length; i++)            hm.Add(S[i], true);             // Iterate over the loop in non decreasing order        for (int startChar = 'Z'; startChar > 'A'; startChar--) {                 // Process further only if current character            // exists in the given string            if (hm.ContainsKey((char)startChar)) {                     // Iterate over all possible common differences                // of AP sequence and update maxLen accordingly                for (int currDiff = 1; currDiff <= 12; currDiff++) {                    int currLen = 1;                         // Iterate over the characters at any interval                    // of current common difference                    for (int ch = startChar - currDiff; ch >= 'A';                        ch -= currDiff) {                        if (hm.ContainsKey((char)ch))                            currLen++;                        else                            break;                    }                         // Update maxLen and other parameters if the currLen                    // is greater than maxLen or if the current                    // difference is smaller than minCommonDifference                    if (currLen > maxLen || (currLen == maxLen                                && currDiff < minCommonDifference)) {                        minCommonDifference = currDiff;                        maxLen = currLen;                        bestStartChar = startChar;                    }                }            }        }        String longestString = "";             // Store the string in decreasing order of        // arithmetic progression        char ch1;        for (int i = bestStartChar;        i >= (bestStartChar - (maxLen - 1) * minCommonDifference);        i -= minCommonDifference)        {            ch1 = (char)i;            longestString += ch1;        }        return longestString;    }     // Driver Code    public static void Main()    {        String S = "ADGJPRT";        Console.WriteLine(findLongestString(S));    }    // This code is contributed by Ryuga}

## Javascript

 // JavaScript Program to find the longest string// with characters arranged in non-decreasing// order of ASCII and in arithmetic progression // Function to find the longest Stringfunction findLongestString(S) {    // Stores the maximum length of required string    let maxLen = 0;     // Stores the optimal starting character of    // required string or arithmetic progression sequence    let bestStartChar;     // Stores the optimal i.e. minimum common difference    // of required string    let minCommonDifference = Number.MAX_SAFE_INTEGER;     let mp = {};    for (let i = 0; i < S.length; i++) {        mp[S[i]] = true;    }     // Iterate over the loop in non decreasing order    for (let startChar = 'Z'.charCodeAt(0); startChar > 'A'.charCodeAt(0);    startChar--) {         // Process further only if current character        // exists in the given string        if (mp[String.fromCharCode(startChar)]) {             // Iterate over all possible common differences            // of AP sequence and update maxLen accordingly            for (let currDiff = 1; currDiff <= 12; currDiff++) {                let currLen = 1;                 // Iterate over the characters at any interval                // of current common difference                for (let ch = startChar - currDiff;                ch >= 'A'.charCodeAt(0); ch -= currDiff) {                    if (mp[String.fromCharCode(ch)]) {                        currLen++;                    } else {                        break;                    }                }                 // Update maxLen and other parameters if the currLen                // is greater than maxLen or if the current                // difference is smaller than minCommonDifference                if (currLen > maxLen || (currLen === maxLen &&                currDiff < minCommonDifference)) {                    minCommonDifference = currDiff;                    maxLen = currLen;                    bestStartChar = startChar;                }            }        }    }    let longestString = "";     // Store the string in decreasing order of    // arithmetic progression    for (let i = bestStartChar; i >= (bestStartChar -    (maxLen - 1) * minCommonDifference); i -= minCommonDifference) {        longestString += String.fromCharCode(i);    }    return longestString;} // Driver Codeconsole.log(findLongestString("ADGJPRT"));

Output

JGDA

Time Complexity : O(|S| + 26*12*26), where |S| is the size of the string.

Space complexity : O(1) as the maximum size of unordered_map “mp” is 26 (for 26 characters in the English alphabet), and the size of the variables “maxLen”, “bestStartChar”, and “minCommonDifference” are constant.

My Personal Notes arrow_drop_up