Javatpoint Logo
Javatpoint Logo

Longest Common Subsequence in Java

The longest subsequence common to all the given sequences is referred to as Longest Common Subsequence. The reason for using the LCS is to restrict the element of the subsequences from occupying the consecutive position within the original sequences.

A sequence that appears in the same relative order, either contiguous or non-contiguous way is known as a subsequence.

For example, if we have two sequences, such as "KTEURFJS" and "TKWIDEUJ", the longest common subsequence will be "TEUJ" of length 4.

In Java, there are two ways to implement the LSC program, i.e., using the recursive method and using dynamic programming. Both the ways have a different implementation.

Longest Common Subsequence in Java

Using Dynamic Programming

This approach is a tabulated implementation for the Longest Common Subsequence. In order to find the Longest Common Subsequence, we use the following steps:

  1. First, we create a table of dimensions (p + 1)*(q + 1) where p and q are the lengths of the given sequences. In the created table, we set 0 to the first row and the first column.
  2. All the remaining cells of the table are filled by using the following steps:
    1. If the characters of the corresponding row and the column are the same and matched successfully, fill the current cell with 1 to the diagonal element and point an arrow to the diagonal cell.
    2. If the characters are not matched, we fill the current cell with the value of the previous column and previous row element. The arrow points to the cell having maximum value, and when the value in both the cells is equal, the arrow will point to any of them.
    3. We repeat step 2 until the complete table is not filled.
    4. The length of the longest common subsequence is the value present in the last row and the last column.
    5. In order to get the LCS, we follow the direction of the arrow from the last element. The elements corresponding to the brackets() are form the longest common subsequence.

Let's implement the code of the Longest Common Subsequence using dynamic programming by following the above steps.


Longest Common Subsequence in Java

Using Recursive Implementation

Let's understand another example of LCS that uses recursive implementation. In this example, we take two sequences from the user and return or print the length of the Longest Common Subsequence.


Longest Common Subsequence in Java

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA