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 Consecuetive Subsequence when only one insert operation is allowed
- Longest Common Subsequence | DP-4
- Longest Common Increasing Subsequence (LCS + LIS)
- LCS (Longest Common Subsequence) of three strings
- Printing Longest Common Subsequence
- C++ Program for Longest Common Subsequence
- Longest Common Anagram Subsequence
- Longest Common Subsequence | DP using Memoization
- Length of longest common subsequence containing vowels
- 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
- Python Program for Longest Common Subsequence
- Java Program for Longest Common Subsequence
- Longest subsequence such that adjacent elements have at least one common digit
- Minimum cost to make Longest Common Subsequence of length k
- Printing Longest Common Subsequence | Set 2 (Printing All)
- Generate permutations with only adjacent swaps allowed
- Minimum insertions to form a palindrome with permutations allowed
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.
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.