Given two strings of lower alphabet characters, we need to find the number of ways to insert a character in the first string such that length of LCS of both strings increases by one.
Input : str1 = “abab”, str2 = “abc” Output : 3 LCS length of given two strings is 2. There are 3 ways of insertion in str1, to increase the LCS length by one which are enumerated below, str1 = “abcab” str2 = “abc” LCS length = 3 str1 = “abacb” str2 = “abc” LCS length = 3 str1 = “ababc” str2 = “abc” LCS length = 3 Input : str1 = “abcabc”, str2 = “abcd” Output : 4
The idea is try all 26 possible characters at each position of first string, if length of str1 is m then a new character can be inserted in (m + 1) positions, now suppose at any time character c is inserted at ith position in str1 then we will match it with all positions having character c in str2. Suppose one such position is j, then for total LCS length to be one more than previous, below condition should satisfy,
LCS(str1[1, m], str2[1, n]) = LCS(str1[1, i], str2[1, j-1]) + LCS(str1[i+1, m], str2[j+1, n])
Above equation states that sum of LCS of the suffix and prefix substrings at inserted character must be same as total LCS of strings, so that when the same character is inserted in first string it will increase the length of LCS by one.
In below code two 2D arrays, lcsl and lcsr are used for storing LCS of prefix and suffix of strings respectively. Method for filling these 2D arrays can be found here.
Please see below code for better understanding,
Time Complexity : O(mn)
Auxiliary Space : O(mn)
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
- Number of ways to insert a character to increase the LCS by one
- Count words that appear exactly two times in an array of words
- Print the string after the specified character has occurred given no. of times
- Count of arrays in which all adjacent elements are such that one of them divide the another
- Check if frequency of all characters can become same by one removal
- Find number of endless points
- Find an equal point in a string of brackets
- Convert Binary fraction to Decimal
- Number of subsequences of the form a^i b^j c^k
- Count of strings that can be formed using a, b and c under given constraints
- Count of AP (Arithmetic Progression) Subsequences in an array
- Check whether two strings are anagram of each other
- Longest Common Subsequence | DP-4
- Find the smallest window in a string containing all characters of another string
- Remove characters from the first string which are present in the second string