Optimizing Arithmetic Progressions in Subsequences
Last Updated :
23 Jul, 2025
Given a string S, a string T is considered good if following 2 conditions hold:
For example, if S = "aaabb" then T = "aab" is good because T is subsequence of S at indices 1,3,5 which is an arithmetic progression. The task is to determine any subsequence that is good string having highest occurrences in the string. Print the number of times that subsequence appears as a good string in the given string.
Examples:
Input: S = "aaabb"
Output: 6
Explanation: "ab" is the good strings with the highest number of occurrences. "ab" occurred 6 times at (1,4), (1,5), (2,4), (2,5), (3,4) and (3,5)
Input: "abcde"
Output: 1
Explanation: "a" is the good string which occurred only once.
Observations:
We observe that if the good string that occurs the most times has length > 2, then there must exist one that occurs just as many times of length exactly 2. This is true because we can always just take the first 2 letters of the good string and still get the answer. Therefore, we only need to check strings of lengths 1 and 2.
Approach: The problem can be solved using the following approach:
The intuition is based on the properties of subsequences and arithmetic progressions. Here's the key idea:
- The problem asks for a good subsequence, which is defined as a subsequence where the indices form an arithmetic progression. This means that the characters in the subsequence are evenly spaced in the original string.
- Count the frequency of each character and each pair of characters in the string. we'll use two arrays, arr1 and arr2, to store these frequencies. arr1[c][/c] is the frequency of character c, and arr2[i][j] is the frequency of pairs of characters i and j where j appears after i in the string.
- Now, iterate over the string and for each character, updates the frequency of that character and all pairs that can be formed with that character. After that, finds the maximum frequency among all characters and all pairs of characters. This maximum frequency is the number of times the most frequent good subsequence appears in the string.
This approach will work because a good subsequence can be either a single character or a pair of characters. A single character is always a good subsequence, and a pair of characters is a good subsequence if and only if the two characters appear at indices that form an arithmetic progression. By counting the frequency of each character and each pair of characters, the code effectively counts the frequency of all possible good subsequences.
Steps to solve the problem:
- Initialize two arrays, arr1 and arr2. arr1 is a 1D array that will store the frequency of each character in the string. arr2 is a 2D array that will store the frequency of each pair of characters in the string.
- Iterate over each character in the string. For each character, do the following:
- Convert the current character to its corresponding index (0-25) by subtracting 'a' from it.
- For each character, add its frequency to the count of pairs with the current character. This is done by adding arr1[j] to arr2[j][c][/c] for all j.
- Increment the frequency of the current character. This is done by incrementing arr1[c][/c].
- Initialize a variable ans to 0.
- Find the maximum frequency among all characters.
- Find the maximum frequency among all pairs of characters.
- Print the maximum frequency, which is the number of times the most frequent good subsequence appears in the string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
// Declare arrays to store the frequency of characters and
// pairs of characters
ll arr1[26], arr2[26][26];
int main()
{
string S = "aaabb";
// Iterate over the string
for (int i = 0; i < S.length(); i++) {
// Convert the current character to its
// corresponding index (0-25)
int c = S[i] - 'a';
// For each character, add its frequency to the
// count of pairs with the current character
for (int j = 0; j < 26; j++)
arr2[j][c] += arr1[j];
// Increment the frequency of the current character
arr1[c]++;
}
// Initialize the maximum frequency to 0
ll ans = 0;
// Find the maximum frequency among all characters
for (int i = 0; i < 26; i++)
ans = max(ans, arr1[i]);
// Find the maximum frequency among all pairs of
// characters
for (int i = 0; i < 26; i++)
for (int j = 0; j < 26; j++)
ans = max(ans, arr2[i][j]);
cout << ans << endl; // Print the maximum frequency
}
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
String S = "aaabb";
// Declare arrays to store the frequency of
// characters and pairs of characters
long[] arr1 = new long[26];
long[][] arr2 = new long[26][26];
// Iterate over the string
for (int i = 0; i < S.length(); i++) {
// Convert the current character to its
// corresponding index (0-25)
int c = S.charAt(i) - 'a';
// For each character, add its frequency to the
// count of pairs with the current character
for (int j = 0; j < 26; j++)
arr2[j][c] += arr1[j];
// Increment the frequency of the current
// character
arr1[c]++;
}
// Initialize the maximum frequency to 0
long ans = 0;
// Find the maximum frequency among all characters
for (int i = 0; i < 26; i++)
ans = Math.max(ans, arr1[i]);
// Find the maximum frequency among all pairs of
// characters
for (int i = 0; i < 26; i++)
for (int j = 0; j < 26; j++)
ans = Math.max(ans, arr2[i][j]);
System.out.println(
ans); // Print the maximum frequency
}
}
Python
# Initialize arrays to store the frequency of characters and pairs of characters
arr1 = [0] * 26
arr2 = [[0] * 26 for _ in range(26)]
# Input string
S = "aaabb"
# Iterate over the string
for i in range(len(S)):
# Convert the current character to its corresponding index (0-25)
c = ord(S[i]) - ord('a')
# For each character, add its frequency to the count of pairs with the current character
for j in range(26):
arr2[j][c] += arr1[j]
# Increment the frequency of the current character
arr1[c] += 1
# Initialize the maximum frequency to 0
ans = 0
# Find the maximum frequency among all characters
for i in range(26):
ans = max(ans, arr1[i])
# Find the maximum frequency among all pairs of characters
for i in range(26):
for j in range(26):
ans = max(ans, arr2[i][j])
print(ans) # Print the maximum frequency
C#
using System;
class GFG {
public static void Main (string[] args) {
string S = "aaabb";
// Declare arrays to store the frequency of characters and
// pairs of characters
long[] arr1 = new long[26];
long[,] arr2 = new long[26, 26];
// Iterate over the string
for (int i = 0; i < S.Length; i++) {
// Convert the current character to its
// corresponding index (0-25)
int c = S[i] - 'a';
// For each character, add its frequency to the
// count of pairs with the current character
for (int j = 0; j < 26; j++)
arr2[j, c] += arr1[j];
// Increment the frequency of the current character
arr1[c]++;
}
// Initialize the maximum frequency to 0
long ans = 0;
// Find the maximum frequency among all characters
for (int i = 0; i < 26; i++)
ans = Math.Max(ans, arr1[i]);
// Find the maximum frequency among all pairs of
// characters
for (int i = 0; i < 26; i++)
for (int j = 0; j < 26; j++)
ans = Math.Max(ans, arr2[i, j]);
Console.WriteLine(ans); // Print the maximum frequency
}
}
JavaScript
function findMaxFrequency(S) {
// Declare arrays to store the frequency of characters and pairs of characters
const arr1 = new Array(26).fill(0);
const arr2 = new Array(26).fill(null).map(() => new Array(26).fill(0));
// Iterate over the string
for (let i = 0; i < S.length; i++) {
// Convert the current character to its corresponding index (0-25)
const c = S.charCodeAt(i) - 'a'.charCodeAt(0);
// For each character, add its frequency to the count of pairs with the current character
for (let j = 0; j < 26; j++) {
arr2[j][c] += arr1[j];
}
// Increment the frequency of the current character
arr1[c]++;
}
// Initialize the maximum frequency to 0
let ans = 0;
// Find the maximum frequency among all characters
for (let i = 0; i < 26; i++) {
ans = Math.max(ans, arr1[i]);
}
// Find the maximum frequency among all pairs of characters
for (let i = 0; i < 26; i++) {
for (let j = 0; j < 26; j++) {
ans = Math.max(ans, arr2[i][j]);
}
}
return ans; // Return the maximum frequency
}
// Example usage
const S = "aaabb";
const result = findMaxFrequency(S);
console.log(result); // Print the maximum frequency
Time Complexity: O(N), where N is the length of the input string S.
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem