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.
- When the current length is more than the maximum length.
- 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++
#include <bits/stdc++.h>
using namespace std;
string findLongestString(string S)
{
int maxLen = 0;
int bestStartChar;
int minCommonDifference = INT_MAX;
unordered_map< char , bool > mp;
for ( int i = 0; i < S.size(); i++)
mp[S[i]] = true ;
for ( int startChar = 'Z' ; startChar > 'A' ; startChar--) {
if (mp[startChar]) {
for ( int currDiff = 1; currDiff <= 12; currDiff++) {
int currLen = 1;
for ( int ch = startChar - currDiff; ch >= 'A' ;
ch -= currDiff) {
if (mp[ch])
currLen++;
else
break ;
}
if (currLen > maxLen || (currLen == maxLen
&& currDiff < minCommonDifference)) {
minCommonDifference = currDiff;
maxLen = currLen;
bestStartChar = startChar;
}
}
}
}
string longestString = "" ;
for ( int i = bestStartChar;
i >= (bestStartChar - (maxLen - 1) * minCommonDifference);
i -= minCommonDifference)
longestString += char (i);
return longestString;
}
int main()
{
string S = "ADGJPRT" ;
cout << findLongestString(S) << endl;
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
public class GFG {
static String findLongestString(String S)
{
int maxLen = 0 ;
int bestStartChar = 0 ;
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 );
for ( int startChar = 'Z' ; startChar > 'A' ; startChar--) {
if (hm.containsKey(( char )startChar)) {
for ( int currDiff = 1 ; currDiff <= 12 ; currDiff++) {
int currLen = 1 ;
for ( int ch = startChar - currDiff; ch >= 'A' ;
ch -= currDiff) {
if (hm.containsKey(( char )ch))
currLen++;
else
break ;
}
if (currLen > maxLen || (currLen == maxLen
&& currDiff < minCommonDifference)) {
minCommonDifference = currDiff;
maxLen = currLen;
bestStartChar = startChar;
}
}
}
}
String longestString = "" ;
char ch;
for ( int i = bestStartChar;
i >= (bestStartChar - (maxLen - 1 ) * minCommonDifference);
i -= minCommonDifference)
{
ch = ( char )i;
longestString += ch;
}
return longestString;
}
public static void main(String args[])
{
String S = "ADGJPRT" ;
System.out.println(findLongestString(S));
}
}
|
Python3
import sys
def findLongestString(S):
maxLen = 0
bestStartChar = 0
minCommonDifference = sys.maxsize
mp = {}
for i in range ( len (S)):
mp[S[i]] = True
for startChar in range ( ord ( 'Z' ), ord ( 'A' ), - 1 ):
if chr (startChar) in mp:
for currDiff in range ( 1 , 13 ):
currLen = 1
for ch in range (startChar - currDiff, ord ( 'A' ) - 1 , - currDiff):
if ( chr (ch) in mp):
currLen + = 1
else :
break
if (currLen > maxLen or (currLen = = maxLen
and currDiff < minCommonDifference)):
minCommonDifference = currDiff
maxLen = currLen
bestStartChar = startChar
longestString = ""
for i in range (bestStartChar,
(bestStartChar - (maxLen - 1 ) * minCommonDifference) - 1 , - minCommonDifference):
longestString + = chr (i)
return longestString
if __name__ = = "__main__" :
S = "ADGJPRT"
print (findLongestString(S))
|
C#
using System;
using System.Collections ;
public class GFG {
static String findLongestString(String S)
{
int maxLen = 0;
int bestStartChar = 0;
int minCommonDifference = Int32.MaxValue ;
Hashtable hm = new Hashtable ();
for ( int i = 0; i < S.Length; i++)
hm.Add(S[i], true );
for ( int startChar = 'Z' ; startChar > 'A' ; startChar--) {
if (hm.ContainsKey(( char )startChar)) {
for ( int currDiff = 1; currDiff <= 12; currDiff++) {
int currLen = 1;
for ( int ch = startChar - currDiff; ch >= 'A' ;
ch -= currDiff) {
if (hm.ContainsKey(( char )ch))
currLen++;
else
break ;
}
if (currLen > maxLen || (currLen == maxLen
&& currDiff < minCommonDifference)) {
minCommonDifference = currDiff;
maxLen = currLen;
bestStartChar = startChar;
}
}
}
}
String longestString = "" ;
char ch1;
for ( int i = bestStartChar;
i >= (bestStartChar - (maxLen - 1) * minCommonDifference);
i -= minCommonDifference)
{
ch1 = ( char )i;
longestString += ch1;
}
return longestString;
}
public static void Main()
{
String S = "ADGJPRT" ;
Console.WriteLine(findLongestString(S));
}
}
|
Javascript
function findLongestString(S) {
let maxLen = 0;
let bestStartChar;
let minCommonDifference = Number.MAX_SAFE_INTEGER;
let mp = {};
for (let i = 0; i < S.length; i++) {
mp[S[i]] = true ;
}
for (let startChar = 'Z' .charCodeAt(0); startChar > 'A' .charCodeAt(0);
startChar--) {
if (mp[String.fromCharCode(startChar)]) {
for (let currDiff = 1; currDiff <= 12; currDiff++) {
let currLen = 1;
for (let ch = startChar - currDiff;
ch >= 'A' .charCodeAt(0); ch -= currDiff) {
if (mp[String.fromCharCode(ch)]) {
currLen++;
} else {
break ;
}
}
if (currLen > maxLen || (currLen === maxLen &&
currDiff < minCommonDifference)) {
minCommonDifference = currDiff;
maxLen = currLen;
bestStartChar = startChar;
}
}
}
}
let longestString = "" ;
for (let i = bestStartChar; i >= (bestStartChar -
(maxLen - 1) * minCommonDifference); i -= minCommonDifference) {
longestString += String.fromCharCode(i);
}
return longestString;
}
console.log(findLongestString( "ADGJPRT" ));
|
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.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
06 Feb, 2023
Like Article
Save Article