Print all longest common sub-sequences in lexicographical order
You are given two strings, the task is to print all the longest common sub-sequences in lexicographical order.
Input : str1 = "abcabcaa", str2 = "acbacba" Output: ababa abaca abcba acaba acaca acbaa acbca
This problem is an extension of longest common subsequence. We first find the length of LCS and store all LCS in a 2D table using Memoization (or Dynamic Programming). Then we search all characters from ‘a’ to ‘z’ (to output sorted order) in both strings. If a character is found in both strings and the current positions of the character lead to LCS, we recursively search all occurrences with current LCS length plus 1.
Below is the implementation of the algorithm.
ababa abaca abcba acaba acaca acbaa acbca
Time Complexity: O(m*n*p), where ‘m’ is the length of the characters array, ‘n’ is the length of array1, and ‘p’ is the length of array2.
Space Complexity: O(m*n), because we are using m*n size 2D matrix for storing the result.
This article is contributed by Shashak Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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 if you want to share more information about the topic discussed above.