Open In App

Find length of the longest non-intersecting anagram Subsequence

Last Updated : 06 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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++;
      }
      else {
        charFrequency = 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));


Output

The 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 the transverse common tangent between the two non intersecting circles
Given two circles of given radii, having there centres a given distance apart, such that the circles don’t touch each other. The task is to find the length of the transverse common tangent between the circles.Examples: Input: r1 = 4, r2 = 6, d = 12 Output: 6.63325 Input: r1 = 7, r2 = 9, d = 21 Output: 13.6015 Approach: Let the radii of the circles
4 min read
Length of direct common tangent between the two non-intersecting Circles
Given two circles, of given radii, have there centres a given distance apart, such that the circles don't touch each other. The task is to find the length of the direct common tangent between the circles.Examples: Input: r1 = 4, r2 = 6, d = 12 Output: 11.8322 Input: r1 = 5, r2 = 9, d = 25 Output: 24.6779 Approach: Let the radii of the circles be r1
4 min read
Longest Common Anagram Subsequence
Given two strings str1 and str2 of length n1 and n2 respectively. The problem is to find the length of the longest subsequence which is present in both the strings in the form of anagrams. Note: The strings contain only lowercase letters. Examples: Input : str1 = "abdacp", str2 = "ckamb" Output : 3 Subsequence of str1 = abc Subsequence of str2 = ca
7 min read
Longest common anagram subsequence from N strings
Given N strings. Find the longest possible subsequence from each of these N strings such that they are anagram to each other. The task is to print the lexicographically largest subsequence among all the subsequences. Examples: Input: s[] = { geeks, esrka, efrsk } Output: ske First string has "eks", Second string has "esk", third string has "esk". T
11 min read
Longest Increasing Subsequence using Longest Common Subsequence Algorithm
Given an array arr[] of N integers, the task is to find and print the Longest Increasing Subsequence.Examples: Input: arr[] = {12, 34, 1, 5, 40, 80} Output: 4 {12, 34, 40, 80} and {1, 5, 40, 80} are the longest increasing subsequences.Input: arr[] = {10, 22, 9, 33, 21, 50, 41, 60, 80} Output: 6 Prerequisite: LCS, LISApproach: The longest increasing
12 min read
Find the centroid of a non-self-intersecting closed Polygon
Given N vertices of the polygon, the task is to find the centroid of the polygonExamples: Input: ar = {{0, 0}, {0, 8}, {8, 8}, {8, 0}} Output: {Cx, Cy} = {4, 4} Input: ar = {{1, 2}, {3, -4}, {6, -7}} Output: {Cx, Cy} = {3.33, -3} Approach: The centroid of a non-self-intersecting closed polygon defined by n vertices (x0, y0), (x1, y1), ..., (xn-1, y
5 min read
Find two non-intersecting String with maximum sum of difference of digits
Given a string S of length N, the task is to find two non-intersecting strings of equal length such that the sum of absolute differences of their digits is maximum and one string should start from starting index of the given string. Note: Both strings will be of the same length. Examples: Input: N = 5, S = "87605"Output: String 1 = "87", String 2 =
10 min read
Find two non-intersecting subarrays having equal sum of all elements raised to the power of 2
Given an array arr[] of positive integers of size N, the task is to check if there exists two non-intersecting subarrays in arr[] such that sum of all possible 2(subarr[i]) and the sum of all possible 2(subarr2[j]) are equal. Examples: Input: arr[] = {4, 3, 0, 1, 2, 0}Output: YESExplanation: Expressing every array element in the form of 2arr[i], th
5 min read
Find 5 non-intersecting ranges with given constraints
Given Five integers A, B, C, D and E. the task is to find five non-intersecting ranges [X1, Y1], [X2, Y2], [X3, Y3], [X4, Y4], [X5, Y5] such that, the following 5 conditions hold. X1 + Y1 = min(A, B)X2 * Y2 = max(A, B)|X3 - Y3| = C?X4 / Y4? = DX5 % Y5 = E Examples: Input: A = 6, B = 36, C = 20, D = 12, E = 55Output: YESExplanation: Let's take, X1 =
6 min read
Length of longest prefix anagram which are common in given two strings
Given two strings str1 and str2 of the lengths of N and M respectively, the task is to find the length of the longest anagram string that is prefix substring of both strings. Examples: Input: str1 = "abaabcdezzwer", str2 = "caaabbttyh"Output: 6Explanation: Prefixes of length 1 of string str1 and str2 are "a", and "c".Prefixes of length 2 of string
8 min read
Article Tags :
Practice Tags :