ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Longest Common Subsequence (LCS) - Dynamic Programming

Java

Goal -- WPM

Ready
Exercise Algorithm Area
1public class LongestCommonSubsequence {
2
3// Main method to find the length of the LCS
4public static int findLCSLength(String text1, String text2) {
5// Handle null or empty input strings
6if (text1 == null || text2 == null) {
7throw new IllegalArgumentException("Input strings cannot be null.");
8}
9
10int m = text1.length();
11int n = text2.length();
12
13// DP table to store lengths of LCS for prefixes
14// dp[i][j] will store the length of LCS of text1[0..i-1] and text2[0..j-1]
15int[][] dp = new int[m + 1][n + 1];
16
17// Build the dp table in a bottom-up manner
18for (int i = 0; i <= m; i++) {
19for (int j = 0; j <= n; j++) {
20// Base case: If either string is empty, LCS is 0
21if (i == 0 || j == 0) {
22dp[i][j] = 0;
23}
24// If characters match, increment LCS length from diagonal
25else if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
26dp[i][j] = dp[i - 1][j - 1] + 1;
27}
28// If characters do not match, take the maximum from top or left
29else {
30dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
31}
32}
33}
34
35// The length of LCS for the entire strings is in dp[m][n]
36return dp[m][n];
37}
38
39// Helper method to reconstruct one of the LCS strings (optional, for demonstration)
40public static String reconstructLCS(String text1, String text2) {
41if (text1 == null || text2 == null) {
42throw new IllegalArgumentException("Input strings cannot be null.");
43}
44
45int m = text1.length();
46int n = text2.length();
47
48int[][] dp = new int[m + 1][n + 1];
49
50for (int i = 0; i <= m; i++) {
51for (int j = 0; j <= n; j++) {
52if (i == 0 || j == 0) {
53dp[i][j] = 0;
54} else if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
55dp[i][j] = dp[i - 1][j - 1] + 1;
56} else {
57dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
58}
59}
60}
61
62// Reconstruct the LCS string by backtracking through the DP table
63StringBuilder lcs = new StringBuilder();
64int i = m, j = n;
65while (i > 0 && j > 0) {
66// If current characters match, they are part of LCS
67if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
68lcs.append(text1.charAt(i - 1));
69i--;
70j--;
71}
72// If not matching, move to the cell that gave the max value
73else if (dp[i - 1][j] > dp[i][j - 1]) {
74i--;
75} else {
76j--;
77}
78}
79
80// The LCS is built in reverse, so reverse it before returning
81return lcs.reverse().toString();
82}
83
84public static void main(String[] args) {
85String s1 = "AGGTAB";
86String s2 = "GXTXAYB";
87System.out.println("Length of LCS is " + findLCSLength(s1, s2)); // Expected: 4
88System.out.println("One LCS is " + reconstructLCS(s1, s2)); // Expected: GTAB
89
90String s3 = "ABCD";
91String s4 = "EFGH";
92System.out.println("Length of LCS is " + findLCSLength(s3, s4)); // Expected: 0
93
94String s5 = "ABC";
95String s6 = "ABC";
96System.out.println("Length of LCS is " + findLCSLength(s5, s6)); // Expected: 3
97
98String s7 = "";
99String s8 = "ABC";
100System.out.println("Length of LCS is " + findLCSLength(s7, s8)); // Expected: 0
101
102String s9 = "ABC";
103String s10 = "";
104System.out.println("Length of LCS is " + findLCSLength(s9, s10)); // Expected: 0
105}
106}
Algorithm description viewbox

Longest Common Subsequence (LCS) - Dynamic Programming

Algorithm description:

This Java code implements the Longest Common Subsequence (LCS) algorithm using dynamic programming. It finds the length of the longest subsequence common to two given strings. A subsequence is formed by deleting zero or more characters from a string without changing the order of the remaining characters. This is a fundamental problem in bioinformatics and text comparison.

Algorithm explanation:

The algorithm uses a 2D DP table, `dp[m+1][n+1]`, where `m` and `n` are the lengths of the two input strings. `dp[i][j]` stores the length of the LCS of the first `i` characters of `text1` and the first `j` characters of `text2`. The table is filled iteratively. If the characters `text1.charAt(i-1)` and `text2.charAt(j-1)` match, `dp[i][j]` is `dp[i-1][j-1] + 1`. If they don't match, `dp[i][j]` takes the maximum value from `dp[i-1][j]` (excluding the current character of `text1`) and `dp[i][j-1]` (excluding the current character of `text2`). The base cases `dp[0][j]` and `dp[i][0]` are initialized to 0, representing an empty string. The time complexity is O(m*n) due to the nested loops filling the DP table. The space complexity is also O(m*n) for the DP table. Edge cases like empty strings or identical strings are handled by the DP table initialization and logic.

Pseudocode:

function findLCSLength(text1, text2):
  m = length(text1)
  n = length(text2)
  create dp table of size (m+1) x (n+1), initialized to 0

  for i from 1 to m:
    for j from 1 to n:
      if text1[i-1] == text2[j-1]:
        dp[i][j] = dp[i-1][j-1] + 1
      else:
        dp[i][j] = max(dp[i-1][j], dp[i][j-1])

  return dp[m][n]

function reconstructLCS(text1, text2):
  // ... (fill dp table as above) ...
  lcs_string = ""
  i = m, j = n
  while i > 0 and j > 0:
    if text1[i-1] == text2[j-1]:
      append text1[i-1] to lcs_string
      i = i - 1
      j = j - 1
    else if dp[i-1][j] > dp[i][j-1]:
      i = i - 1
    else:
      j = j - 1
  reverse lcs_string
  return lcs_string