![]() |
VOOZH | about |
Given two strings s1 and s2 consisting of lowercase English letters of length n1 and n2 respectively, find the number of ways to insert exactly one character into string s1 such that the length of the Longest Common Subsequence (LCS) of both strings increases by exactly 1.
Examples:
Input: s1 = "abab", s2 = "abc"
Output: 3
Explanation: The LCS length of the given two strings is 2. There are 3 valid insertions in s1 which increase the LCS length to 3:
"abcab" -> LCS = 3
"abacb" -> LCS = 3
"ababc" -> LCS = 3Input: s1 = "abcabc", s2 = "abcd"
Output: 4
Explanation: The LCS length of the given two strings is 3. There are 4 valid insertions in s1 which increase the LCS length to 4:
"abcdabc" -> LCS = 4
"abcadcb" -> LCS = 4
"abcabdc" -> LCS = 4
"abcabcd" -> LCS = 4
Table of Content
The idea is to simulate the insertion of every possible lowercase character (a to z) at every possible position in s1 and compute the LCS of the modified s1 with s2. If the LCS length increases by one after the insertion, we count it as a valid way. This approach checks all possible combinations of insertions and directly verifies whether the LCS length increases.
Note : The DP solution of the LCS problem has been directly used in the code below.
3
The idea is to avoid recomputing LCS for every insertion by using precomputed results. When a character is inserted into s1, the effect on LCS can be split into three parts: prefix before the insertion, suffix after it, and the contribution of the inserted character.
Instead of recalculating LCS each time, we precompute LCS of all prefixes and suffixes of both strings.
After preprocessing, we try inserting each character from 'a' to 'z' at every position in s1. For each insertion, we check whether there exists a matching position in s2 such that the prefix LCS + suffix LCS equals the original LCS. If this condition is satisfied, the insertion increases LCS by exactly 1. Finally, we count all such valid insertions.
Consider the strings: s1 = "abab" and s2 = "abc"
Step 1: First, compute the LCS of both strings. LCS of "abab" and "abc" is "ab". So, baseLCS = 2
Step 2: Precompute required data:
Step 3: Now, try inserting a character into s1 at different positions. For example, insert 'c' at index 2: s1 becomes "abcab", and we match 'c' with position p = 3 in s2.
Step 4: We check the condition: lcsl[i][pā1] + lcsr[i+1][p+1] = baseLCS. Here, the left contribution is 2 and the right is 0, so: 2 + 0 = 2 = baseLCS
Step 5: Therefore, the existing LCS is preserved, and the inserted character contributes an additional match, increasing the LCS by exactly 1.
Step 6: Similarly, other valid insertions include "abacb" and "ababc". Therefore, the total number of valid ways = 3.
3