We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I was confused about the same thing, but apparently
you only count common subsequences that begin with the first item of the second substring. This way there are no duplicates counted.
ex.
try your example: "abcdab"
t=1: "a", "bcdab"
you don't count anything because no common subsequence begins with 'b', the first char of the second substring.
t=2: "ab", "cdab"
you don't count anything because no common subsequence begins with 'c'
t=3: "abc", "dab"
you still don't count anything (same reason, now 'd')
t=4: "abcd", "ab"
"a" and "ab" begin with 'a', so there are 2 common subsequences we want
t=5: "abcda", "b"
"b" begins with 'b', so there is 1.
total is 3, as expected.
Programmaticaly, we only initialize the dp array for the first item of the second substring with all items of the first substring. (dp[0][n])
Note that the solution reverses the two substrings (passes the second substring as the first) which is why it's not setting dp[n][0] instead.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Square Subsequences
You are viewing a single comment's thread. Return to all comments →
I was confused about the same thing, but apparently you only count common subsequences that begin with the first item of the second substring. This way there are no duplicates counted.
ex.
try your example: "abcdab"
t=1: "a", "bcdab"
you don't count anything because no common subsequence begins with 'b', the first char of the second substring.
t=2: "ab", "cdab"
you don't count anything because no common subsequence begins with 'c'
t=3: "abc", "dab"
you still don't count anything (same reason, now 'd')
t=4: "abcd", "ab"
"a" and "ab" begin with 'a', so there are 2 common subsequences we want
t=5: "abcda", "b"
"b" begins with 'b', so there is 1.
total is 3, as expected.
Programmaticaly, we only initialize the dp array for the first item of the second substring with all items of the first substring. (dp[0][n])
Note that the solution reverses the two substrings (passes the second substring as the first) which is why it's not setting dp[n][0] instead.