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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to find the longest string
// with characters arranged in non-decreasing
// order of ASCII and in arithmetic progression
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the longest String
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;
  
    // Stores the optimal i.e. minimum common difference
    // of required string
    int minCommonDifference = INT_MAX;
  
    unordered_map<char, bool> 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 Code
int main()
{
    string S = "ADGJPRT";
    cout << findLongestString(S) << endl;
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to find the longest string
// with characters arranged in non-decreasing
// order of ASCII and in arithmetic progression
import 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 <Character, Boolean> hm = new HashMap
                                <Character, Boolean>();
        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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 

chevron_right


Output:

JGDA

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



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 : Nishant Tanwar, AnkitRai01