Find length of the longest non-intersecting anagram Subsequence
Last Updated :
06 Mar, 2023
Given a string S of length N, find the length of the two longest non-intersecting subsequences in S that are anagrams of each other.
Input: S = "aaababcd"
Output: 3
Explanation: Index of characters in the 2 subsequences are:
- {0, 1, 3} = {a, a, b}
- {2, 4, 5} = {a, a, b}
The above two subsequences of S are anagrams.
- Frequency of 'a' = 4, so 2 'a's can be used in both the anagrams.
- Frequency of 'b' = 2, so 1 'a' can be used in both the anagrams.
Hence 2 + 1 = 3 is the length of two longest subsequence in S that are anagrams of each other.
Input: S = "geeksforgeeks"
Output: 5
Explanation: The two longest subsequences that are anagrams of one another are "geeks"(0, 4) and "geeks"(8, 12), each of length 5.
Approach: To solve the problem follow the below idea:
The approach calculates the maximum length of a subsequence of anagrams by dividing each character frequency by 2 and taking the floor. This is because each character can appear at most 2 times in a subsequence of anagrams. For example, if the frequency of a character is 3, we can use 2 of those in a subsequence of anagrams. Hence, we take the floor of half of its frequency to get the maximum number of times it can be used. Adding the result for each character gives us the final answer which is the length of the longest subsequence of anagrams.
Below are the steps for the above approach:
- Initialize an array count[] to store the frequency of each character in the string S.
- Then, we loop through each character in the string S and count the frequency of each character.
- If a character is not in the count[] array, we set its frequency to 1.
- If a character already exists in the count[] array, we increment its frequency by 1.
- Iterate the array count[] and divide each value i.e the frequency of each character by 2 and take the floor value and add the variable sum to get the maximum length of the two longest subsequences of S that are anagrams of one another.
Below is the implementation for the above approach:
C++
// Program to find the length of the two
// longest subsequences in the string that
// are anagrams of each other
#include <bits/stdc++.h
using namespace std;
int maxLengthOfAnagramSubsequence(string s)
{
// Count the frequency of each
// character in the string
int count[26] = { 0 };
for (int i = 0; i < s.length(); i++)
count[s[i] - 'a']++;
// Calculate the sum of frequency of
// each character divided by 2 Round
// down to the nearest integer
int sum = 0;
for (int i = 0; i < 26; i++)
sum += count[i] / 2;
// Return the sum as the answer
return sum;
}
// Drivers code
int main()
{
string s = "aabcdabcd";
// Function call
cout << maxLengthOfAnagramSubsequence(s) << endl;
return 0;
}
Java
// Program to find the length of the two longest subsequences in the string that are anagrams of each other
import java.util.HashMap;
public class GFG {
public static int longestAnagramSubsequence(String S)
{
int maxLength = 0;
HashMap<Character, Integer> charFrequency
= new HashMap<>();
// Count the frequency of each character in the
// string
for (int i = 0; i < S.length(); i++) {
char c = S.charAt(i);
charFrequency.put(
c, charFrequency.getOrDefault(c, 0) + 1);
}
// Calculate the sum of frequency of each character
// divided by 2 Round down to the nearest integer
for (int value : charFrequency.values()) {
maxLength += value / 2;
}
// Return the sum as the answer
return maxLength;
}
public static void main(String[] args)
{
String S1 = "aaababcd";
System.out.println(
"The length of the two longest subsequences of "
+ S1 + " that are anagrams of one another: "
+ longestAnagramSubsequence(S1));
}
}
Python
def maxLengthOfAnagramSubsequence(s):
# Count the frequency of each character in the string
count = [0] * 26
for i in range(len(s)):
count[ord(s[i]) - ord('a')] += 1
# Calculate the sum of frequency of each character divided by 2
# Round down to the nearest integer
sum = 0
for i in range(26):
sum += count[i] // 2
# Return the sum as the answer
return sum
# Drivers code
s = "aabcdabcd"
# Function call
print(maxLengthOfAnagramSubsequence(s))
C#
// C# Program to find the length of the two longest
// subsequences in the string that are anagrams of each
// other
using System;
using System.Collections.Generic;
public class GFG {
static int longestAnagramSubsequence(string S)
{
int maxLength = 0;
Dictionary<char, int> charFrequency
= new Dictionary<char, int>();
// Count the frequency of each character in the
// string
foreach(char c in S)
{
if (charFrequency.ContainsKey(c)) {
charFrequency[c]++;
}
else {
charFrequency[c] = 1;
}
}
// Calculate the sum of frequency of each character
// divided by 2 Round down to the nearest integer
foreach(int value in charFrequency.Values)
{
maxLength += value / 2;
}
// Return the sum as the answer
return maxLength;
}
static public void Main()
{
// Code
string S1 = "aaababcd";
Console.WriteLine(
"The length of the two longest subsequences of "
+ S1 + " that are anagrams of one another: "
+ longestAnagramSubsequence(S1));
}
}
// This code is contributed by sankar.
JavaScript
function maxLengthOfAnagramSubsequence(s) {
// Count the frequency of each character in the string
const count = new Array(26).fill(0);
for (let i = 0; i < s.length; i++) {
count[s.charCodeAt(i) - 'a'.charCodeAt(0)]++;
}
// Calculate the sum of frequency of each character divided by 2
// Round down to the nearest integer
let sum = 0;
for (let i = 0; i < 26; i++) {
sum += Math.floor(count[i] / 2);
}
// Return the sum as the answer
return sum;
}
// Drivers code
const s = "aabcdabcd";
// Function call
console.log(maxLengthOfAnagramSubsequence(s));
OutputThe length of the two longest subsequences of aaababcd that are anagrams of one another: 3
Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(1)
Similar Reads
Length of longest common subsequence containing vowels Given two strings X and Y of length m and n respectively. The problem is to find the length of the longest common subsequence of strings X and Y which contains all vowel characters.Examples: Input : X = "aieef" Y = "klaief"Output : aieInput : X = "geeksforgeeks" Y = "feroeeks"Output : eoeeSource:Pay
14 min read
Length of longest subsequence consisting of distinct adjacent elements Given an array arr[], the task is to find the length of the longest subsequence of the array arr[] such that all adjacent elements in the subsequence are different. Examples: Input: arr[] = {4, 2, 3, 4, 3}Output: 5Explanation:The longest subsequence where no two adjacent elements are equal is {4, 2,
5 min read
Longest subsequence consisting of alternate vowels and consonants Given a non-empty string S, the task is to print the longest subsequence from the string S which contains alternating vowels and consonants. Note: If multiple such subsequences exist having the same length, print the subsequence having the maximum sum of ASCII values of its characters.Examples: Inpu
13 min read
Length of the longest increasing subsequence which does not contain a given sequence as Subarray Given two arrays arr[] and arr1[] of lengths N and M respectively, the task is to find the longest increasing subsequence of array arr[] such that it does not contain array arr1[] as subarray. Examples: Input: arr[] = {5, 3, 9, 3, 4, 7}, arr1[] = {3, 3, 7}Output: 4Explanation: Required longest incre
14 min read
Longest subsequence with consecutive English alphabets Given string S, the task is to find the length of the longest subsequence of the consecutive lowercase alphabets. Examples: Input: S = "acbdcfhg"Output: 3Explanation: String "abc" is the longest subsequence of consecutive lowercase alphabets.Therefore, print 3 as it is the length of the subsequence
6 min read