**By: Saurav**

**2018-04-07 05:20:00 UTC**

These three tough looking problems are based on the same concept. let's solve the first one and identify the subproblem and guess the solution for the base case.

Given two sequences, find the length of longest subsequence 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”. So a string of length n has 2^n different possible subsequences.

**LONGEST COMMON SUB SEQUENCE **

A simple strategy is to go and find out each substring of the two inputs. As we know that will be exponential complexity as the total number of solutions will be 2**n.

A simpler problem can be to take the last characters of the two strings.

If they are equal, add 1 to whatever is the result of the subproblems consisting of a substring in the two strings without the last one. That means longest common subsequence at last index would be 1 + the result we get from the remaining substrings. If they are not equal, it will be the maximum of alternate substrings.

A graph structure like below explains the recursive tree

We see that lcs(“AXY”, “AYZ”) is being solved two times. Now that we understand that there is a substructure involved, lets use dynamic programming to solve this optimally:

if you run it, you will see all our tests pass and we expected results.

** LONGEST REPEATING SUB SEQUENCE **

Now let's move on to the second and third question which is derived from the first one. Now, I want to find the repeated subsequence. Since the first one solves the common subsequence between two strings, the only thing to check if we compare a string with itself is the index of the subsequence should not be the same and yet the elements are the same and then we will get a new subsequence which is repeated in the string itself.

Lets modify the algorithm to handle the new requirement:

**REPEATED SUB SEQUENCE OF LENGTH 2 OR MORE**

The only thing to add to the previous code is a check that our code returns a length more than 2:

Owned & Maintained by Saurav Prakash

If you like what you see, you can help me cover server costs or buy me a cup of coffee though donation :)