Improve Article
Save Article
Improve Article
Save Article
Given a drawstring S of magnitude N, find nan magnitude of nan 2 longest non-intersecting subsequences successful S that are anagrams of each other.
Input: S = “aaababcd”
Output: 3
Explanation: Index of characters successful nan 2 subsequences are:
- {0, 1, 3} = {a, a, b}
- {2, 4, 5} = {a, a, b}
The supra 2 subsequences of S are anagrams.
- Frequency of ‘a’ = 4, truthful 2 ‘a’s tin beryllium utilized successful some nan anagrams.
- Frequency of ‘b’ = 2, truthful 1 ‘a’ tin beryllium utilized successful some nan anagrams.
Hence 2 + 1 = 3 is nan magnitude of 2 longest subsequence successful S that are anagrams of each other.
Input: S = “geeksforgeeks”
Output: 5
Explanation: The 2 longest subsequences that are anagrams of 1 different are “geeks”(0, 3) and “geeks”(8, 12), each of magnitude 5.
Approach: To lick nan problem travel nan beneath idea:
The attack calculates nan maximum magnitude of a subsequence of anagrams by dividing each characteristic wave by 2 and taking nan floor. This is because each characteristic tin look astatine astir 2 times successful a subsequence of anagrams. For example, if nan wave of a characteristic is 3, we tin usage 2 of those successful a subsequence of anagrams. Hence, we return nan level of half of its wave to get nan maximum number of times it tin beryllium used. Adding nan consequence for each characteristic gives america nan last reply which is nan magnitude of nan longest subsequence of anagrams.
Below are nan steps for nan supra approach:
- Initialize an array count[] to shop nan wave of each characteristic successful nan drawstring S.
- Then, we loop done each characteristic successful nan drawstring S and count nan wave of each character.
- If a characteristic is not successful nan count[] array, we group its wave to 1.
- If a characteristic already exists successful nan count[] array, we increment its wave by 1.
- Iterate nan array count[] and disagreement each worth i.e nan wave of each characteristic by 2 and return nan level worth and adhd nan adaptable sum to get nan maximum magnitude of nan 2 longest subsequences of S that are anagrams of 1 another.
Below is nan implementation for nan supra approach:
C++
Java
Output
The magnitude of nan 2 longest subsequences of aaababcd that are anagrams of 1 another: 3Time Complexity: O(N), wherever N is nan magnitude of nan string.
Auxiliary Space: O(1)