4

General problem of Longest common Subsequence ( to be used as LCS hereafter) :-

Given two Strings, find the length of LCS present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous.

For example:- “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg”. but “acb”, “age”... etc. are not.

We can use dynamic programming to find solution for this in O(nm) where n and m are length of string respectively. Here is the pseudocode for the same: -

Procedure LCSlength(s1, s2):
Table[0][0] = 0
for i from 1 to s1.length
    Table[0][i] = 0
endfor
for i from 1 to s2.length
    Table[i][0] = 0
endfor
for i from 1 to s2.length
    for j from 1 to s1.length
        if s2[i] equals to s1[j]
            Table[i][j] = Table[i-1][j-1] + 1
        else
            Table[i][j] = max(Table[i-1][j], Table[i][j-1])
        endif
    endfor
endfor
Return Table[s2.length][s1.length]

However Now I have several queries of the form [L,R] and in each query i have to find length of LCS of string1 and substring of string2 ie.(s2[L] s2[L+1].....s2[R]).

For Example:-

s1= "aacdef"

s2= "aaxcef"

query [0,3]: - s1= "aacdef"

               s2= "aaxc"

               length of LCS of s1 and s2 = 3 (LCS = "aac")

query [2,5]: - s1= "aacdef"

               s2= "xcef"

               length of LCS of s1 and s2 = 3 (LCS = "cef")

One Brute force method is to simply run the general LCS solution every time a new query is asked. However if number of queries are large, its time complexity will become very large. So, can we do better than this?

code_it
  • 131
  • 7
  • 1
    You make several **bold** statements. Very **bold** statements. – user4581301 Jul 27 '21 at 20:16
  • Really interesting! What I can think of is that we can use a 2d array to record all results of legal indexes pairs. Before simply run the general LCS solution every time we can search result in the array. – prettypig Jul 30 '21 at 09:18
  • @prettypig how are you storing the answer for all legal index pair in your 2d array? – code_it Jul 30 '21 at 19:06
  • I think I know how to solve the problem. Can you give me some problem link of online judge where I can submit and test my solution. – risingStark Jul 31 '21 at 14:41
  • @risingStark I don't know whether it exists on any Online judge Or not but i came up with this question myself. So it would be great if you could just tell your approach. – code_it Aug 02 '21 at 12:53
  • 1
    @code_it I think although I am not sure, that it can be solved by using the already generated `table[i][j]`. This 2D array `table[i][j]` stores the LCS of string1 upto `i`th index and string2 till `j`th index. Now, you need the LCS of complete string1 (length n) and substring of string2 for `[l, r`], you can use `table[n-1][r] - table[n-1][l-1]` – risingStark Aug 04 '21 at 17:51

0 Answers0