Given two strings in lowercase, find the longest string whose permutations are subsequences of given two strings. The output longest string must be sorted.
Input : str1 = "pink", str2 = "kite" Output : "ik" The string "ik" is the longest sorted string whose one permutation "ik" is subsequence of "pink" and another permutation "ki" is subsequence of "kite". Input : str1 = "working", str2 = "women" Output : "now" Input : str1 = "geeks" , str2 = "cake" Output : "ek" Input : str1 = "aaaa" , str2 = "baba" Output : "aa"
The idea is to count characters in both strings.
- calculate frequency of characters for each string and store them in their respective count arrays, say count1 for str1 and count2 for str2.
- Now we have count arrays for 26 characters. So traverse count1 and for any index ‘i’ append character (‘a’+i) in resultant string ‘result’ by min(count1[i], count2[i]) times.
- Since we traverse count array in ascending order, our final string characters will be in sorted order.
- Longest Common Subsequence with at most k changes allowed
- Longest Common Subsequence | DP-4
- Longest Common Subsequence | DP using Memoization
- C++ Program for Longest Common Subsequence
- LCS (Longest Common Subsequence) of three strings
- Longest Common Anagram Subsequence
- Printing Longest Common Subsequence
- Longest Common Increasing Subsequence (LCS + LIS)
- Length of longest common subsequence containing vowels
- Python Program for Longest Common Subsequence
- Java Program for Longest Common Subsequence
- Edit distance and LCS (Longest Common Subsequence)
- Longest common anagram subsequence from N strings
- Longest Subsequence with at least one common digit in every element
- Longest subsequence such that adjacent elements have at least one common digit
Time Complexity: O(m + n) where m and n are lengths of input strings.
Auxiliary Space: O(1)
If you have another approach to solve this problem then please share.
This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.