Lexicographically smallest and largest anagrams of a string containing another string as its substring
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: S1 = “hheftaabzzdr”, S2 = “earth”
Output: abdearthfhzz, zzhfearthdba
The smallest anagram of the given string S1 with S2 as a substring is “abdearthfhzz”
The largest anagram of the given string S1 with s2 as a substring is “zzhfearthdba”
Input: S1 = “ethgakagmenpgs”, S2 = “geeks”
Output: aageeksgghmnpt, tpmnhgggeeksaa
The smallest anagram of the given string S1 with S2 as a substring is “aageeksgghmnpt”
The largest anagram of the given string S1 with S2 as a substring is “tpmnhgggeeksaa”
Naive Approach: The simplest approach is to find all possible anagrams of S1 and check if any of those anagrams contain S2 as a substring or not. If yes, then find the lexicographically smallest and the largest among them.
Time Complexity: O(N!)
Auxiliary Space: O(N)
Efficient Approach: The idea is to first generate the lexicographically smallest anagram character by character and then find the lexicographically largest anagram by reversing the smallest anagram except for the substring which contains S2. Below are the steps:
- Initialize a map M and store the frequency of each character present in S1
- Maintain a Set S which stores the distinct characters present in S1.
- Decrease the frequency of characters of S1 from M which are already present in S2.
- Initialize an empty string res which will store the lexicographically largest anagram.
- Iterate over the set S, if the first character of string S2 is encountered while traversing the set values, check if the second distinct character of S2 is greater than the current character of Set. If so, then add all the characters of S2 to res.
- Otherwise, keep on iterating the Set and add the characters to res.
Below is the implementation of the above approach:
Time Complexity: O(N+M)
Auxiliary Space: O(N)