A Space Optimized Solution of LCS
Last Updated :
18 Nov, 2024
Given two strings, s1 and s2, the task is to find the length of the Longest Common Subsequence. If there is no common subsequence, return 0
.
Examples:
Input: s1 = “ABCDGH”, s2 = “AEDFHR”
Output: 3
Explanation: The longest subsequence present in both strings is "ADH".
Input: s1 = “AGGTAB”, s2 = “GXTXAYB”
Output: 4
Explanation: The longest subsequence present in both strings is "GTAB".
We have discussed a typical dynamic programming-based solution for LCS.
How to find the length of LCS in O(n) auxiliary space?
One important observation in the above simple implementation is, in each iteration of the outer loop we only need values from all columns of the previous row. So there is no need to store all rows in our dp matrix, we can just store two rows at a time and use them. In that way, used space will be reduced from dp[m+1][n+1] to dp[2][n+1].
The recurrence relation for the Longest Common Subsequence (LCS) problem is:
If the last character of s1 and s2 match:
- dp[i][j] = 1 + dp[i-1][j-1]
if the last characters of s1 and s2 do not match, we take the maximum of two cases:
1. exclude the last character of s1
2. exclude the last char of s2
- dp[i][j] = max(dp[i-1][j],dp[i][j-1])
Base Case: when the length of either s1 or s2 is 0, LCS is 0.
- for i = 0 or j = 0 dp[i][j] = 0
In the recurrance relation one things that we can observe is for finding the current state dp[i][j] we don't need to store the entire table, we only need to store the current row and the previous row because each value at position (i, j) in the table only depends on:
- The value directly above it (dp[i-1][j]),
- The value directly to the left (dp[i][j-1]),
- The value diagonally left above it (dp[i-1][j-1]).
Since only the previous row and the current row are required to compute the LCS, we can reduce the space complexity by using just two rows instead of the entire table. We use a 2D array of size 2 x (n+1) to store only two rows at a time.
We have used two array to store the previous and current row, prev for previous row and curr for current row, once the iteration for current row is done, we will set prev = curr, so that curr row can serve as prev for next index.
C++
// C++ program to find the longest common subsequence of two strings
// using space optimization
#include <bits/stdc++.h>
using namespace std;
int lcs(string& s1, string& s2) {
int n = s1.size();
int m = s2.size();
// Initialize two vectors to store the current
// and previous rows of the DP table
vector<int> prev(m + 1, 0), cur(m + 1, 0);
// Base case is covered as we have initialized
// the prev and cur vectors to 0.
for (int ind1 = 1; ind1 <= n; ind1++) {
for (int ind2 = 1; ind2 <= m; ind2++) {
if (s1[ind1 - 1] == s2[ind2 - 1]) {
// Characters match, increment LCS length
cur[ind2] = 1 + prev[ind2 - 1];
}
else
// Characters don't match, consider the
// maximum from above or left
cur[ind2] = max(prev[ind2], cur[ind2 - 1]);
}
// Update the previous row with the current row
prev = cur;
}
// Return the length of the Longest Common Subsequence
return prev[m];
}
int main() {
string s1 = "AGGTAB";
string s2 = "GXTXAYB";
int res = lcs(s1, s2);
cout << res;
return 0;
}
Java
// Java program to find the longest common subsequence of
// two strings using space optimization
class GfG {
static int lcs(String s1, String s2) {
int n = s1.length();
int m = s2.length();
// Create arrays to store the LCS lengths
int prev[] = new int[m + 1];
int cur[] = new int[m + 1];
// Iterate through the strings and calculate LCS
// lengths
for (int ind1 = 1; ind1 <= n; ind1++) {
for (int ind2 = 1; ind2 <= m; ind2++) {
// If the characters at the current indices
// are the same, increment the LCS length
if (s1.charAt(ind1 - 1)
== s2.charAt(ind2 - 1))
cur[ind2] = 1 + prev[ind2 - 1];
// If the characters are different, choose
// the maximum LCS length by either
// excluding a character in s1 or excluding
// a character in s2
else
cur[ind2] = Math.max(prev[ind2],
cur[ind2 - 1]);
}
// Update the 'prev' array to the values of
// 'cur' for the next iteration
prev = (int[])(cur.clone());
}
// Return the length of the Longest Common
// Subsequence (LCS)
return prev[m];
}
public static void main(String[] args) {
String s1 = "AGGTAB";
String s2 = "GXTXAYB";
int res = lcs(s1, s2);
System.out.println(res);
}
}
Python
# Python program to find the longest common subsequence (LCS)
# using space optimization
def lcs(s1, s2):
n = len(s1)
m = len(s2)
# Initialize two arrays, 'prev' and 'cur',
# to store the DP values
prev = [0] * (m + 1)
cur = [0] * (m + 1)
# Loop through the characters of both strings
# to compute LCS
for ind1 in range(1, n + 1):
for ind2 in range(1, m + 1):
if s1[ind1 - 1] == s2[ind2 - 1]:
# If the characters match, increment
# LCS length by 1
cur[ind2] = 1 + prev[ind2 - 1]
else:
# If the characters do not match, take
# the maximum of LCS
# by excluding one character from s1 or s2
cur[ind2] = max(prev[ind2], cur[ind2 - 1])
# Update 'prev' to be the same as 'cur' for the
# next iteration
prev = cur[:]
# The value in 'prev[m]' represents the length of the
# Longest Common Subsequence
return prev[m]
if __name__ == "__main__":
s1 = "AGGTAB"
s2 = "GXTXAYB"
print(lcs(s1, s2))
C#
// C# program to find the longest common subsequence (LCS)
// using space optimization
using System;
class GfG {
static int lcs(string s1, string s2) {
int n = s1.Length;
int m = s2.Length;
// Initialize two arrays to store the current
// and previous rows of the DP table
int[] prev = new int[m + 1];
int[] cur = new int[m + 1];
// Base case is implicitly handled as the arrays are
// initialized to 0
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (s1[i - 1] == s2[j - 1]) {
// Characters match, increment LCS
// length
cur[j] = 1 + prev[j - 1];
}
else {
// Characters don't match, consider the
// maximum from above or left
cur[j] = Math.Max(prev[j], cur[j - 1]);
}
}
// Update the previous row with
// the current row
Array.Copy(cur, prev, m + 1);
}
// Return the length of the Longest Common
// Subsequence
return prev[m];
}
static void Main() {
string s1 = "AGGTAB";
string s2 = "GXTXAYB";
int res = lcs(s1, s2);
Console.WriteLine(res);
}
}
JavaScript
// JavaScript program to find the longest common subsequence
// (LCS) using space optimization
function lcs(s1, s2) {
const n = s1.length;
const m = s2.length;
// Initialize arrays 'prev' and 'cur' to store dynamic
// programming results, both initialized with 0
const prev = new Array(m + 1).fill(0);
const cur = new Array(m + 1).fill(0);
// Base case is already covered as 'prev' and 'cur' are
// initialized to 0.
// Populating the 'cur' array using nested loops
for (let ind1 = 1; ind1 <= n; ind1++) {
for (let ind2 = 1; ind2 <= m; ind2++) {
if (s1[ind1 - 1] === s2[ind2 - 1]) {
cur[ind2] = 1 + prev[ind2 - 1];
}
else {
cur[ind2]
= Math.max(prev[ind2], cur[ind2 - 1]);
}
}
// Update 'prev' with the values of 'cur' for the
// next iteration
prev.splice(0, m + 1, ...cur);
}
// The result is stored in the last element of the
// 'prev' array
return prev[m];
}
const s1 = "AGGTAB";
const s2 = "GXTXAYB";
const res = lcs(s1, s2);
console.log(res);
Time Complexity : O(m*n), where m
is the length of string s1
and n
is the length of string s2.
Auxiliary Space: O(2n), Only two 1D arrays are used, each of size m+1.
Using Single Array - O(m*n) Time and O(n) Space
In this approach, the space complexity is further optimized by using a single DP array, where:
dp[j] represents the value of dp[i-1][j] (previous row's value) before updating. During the computation, dp[j] is updated to represent the current row value dp[i][j]
Now the recurrance relations become:
- if the characters s1[i-1] and s2[j-1] match, dp[j] = 1+ prev. Here, prev is a temporary variable storing the diagonal value (dp[i-1][j-1]).
- If the characters don't match, dp[j] = max(dp[j-1], dp[j]). Here dp[j] represents the value of dp[i-1][j] before updating and dp[j-1] represents the value of dp[i-1][j].
C++
// C++ program to find the longest common subsequence of two strings
// using space optimization
#include <iostream>
#include <vector>
using namespace std;
int lcs(string &s1, string &s2) {
int m = s1.length(), n = s2.length();
// dp vector is initialized to all zeros
// This vector stores the LCS values for the current row.
// dp[j] represents LCS of s1[0..i] and s2[0..j]
vector<int> dp(n + 1, 0);
// i and j represent the lengths of s1 and s2 respectively
for (int i = 1; i <= m; ++i) {
// prev stores the value from the previous
// row and previous column (i-1), (j -1)
// Used to keep track of LCS[i-1][j-1] while updating dp[j]
int prev = dp[0];
for (int j = 1; j <= n; ++j) {
// temp temporarily stores the current
// dp[j] before it gets updated
int temp = dp[j];
// If characters match, add 1 to the value
// from the previous row and previous column
// dp[j] = 1 + LCS[i-1][j-1]
if (s1[i - 1] == s2[j - 1])
dp[j] = 1 + prev;
else
// Otherwise, take the maximum of the
// left (dp[j-1]) and top (dp[j]) values
dp[j] = max(dp[j - 1], dp[j]);
// Update prev for the next iteration
// This keeps the value of the previous
// row (i-1) for future comparisons
prev = temp;
}
}
// The last element of the vector contains the length of the LCS
// dp[n] stores the length of LCS of s1[0..m] and s2[0..n]
return dp[n];
}
int main() {
string s1 = "AGGTAB", s2 = "GXTXAYB";
cout << lcs(s1, s2);
return 0;
}
Java
// Java program to find the longest common subsequence of two strings
// using space optimization
class GfG {
static int lcs(String s1, String s2) {
int m = s1.length();
int n = s2.length();
// dp array is initialized to all zeros
int[] dp = new int[n + 1];
// i and j represent the lengths of s1 and s2 respectively
for (int i = 1; i <= m; ++i) {
// prev stores the value from the previous
// row and previous column (i-1), (j -1)
int prev = dp[0];
for (int j = 1; j <= n; ++j) {
// temp temporarily stores the current
// dp[j] before it gets updated
int temp = dp[j];
if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
// If characters match, add 1 to the value
// from the previous row and previous column
dp[j] = 1 + prev;
} else {
// Otherwise, take the maximum of the
// left and top values
dp[j] = Math.max(dp[j - 1], dp[j]);
}
// Update prev for the next iteration
prev = temp;
}
}
// The last element of the array contains
// the length of the LCS
return dp[n];
}
public static void main(String[] args) {
String s1 = "AGGTAB";
String s2 = "GXTXAYB";
int res = lcs(s1, s2);
System.out.println(res);
}
}
Python
# Python program to find the longest common subsequence of two strings
# using space optimization
def lcs(s1, s2):
m = len(s1)
n = len(s2)
# dp array is initialized to all zeros
dp = [0] * (n + 1)
# i and j represent the lengths of s1
# and s2 respectively
for i in range(1, m + 1):
# prev stores the value from the previous
# row and previous column (i-1), (j -1)
prev = dp[0]
for j in range(1, n + 1):
# temp temporarily stores the current
# dp[j] before it gets updated
temp = dp[j]
if s1[i - 1] == s2[j - 1]:
# If characters match, add 1 to the value
# from the previous row and previous column
dp[j] = 1 + prev
else:
# Otherwise, take the maximum of the
# left and top values
dp[j] = max(dp[j - 1], dp[j])
# Update prev for the next iteration
prev = temp
# The last element of the list contains
# the length of the LCS
return dp[n]
if __name__ == "__main__":
s1 = "AGGTAB"
s2 = "GXTXAYB"
res = lcs(s1, s2)
print(res)
C#
// C# program to find the longest common subsequence of two strings
// using space optimization
using System;
class GfG {
static int lcs(string s1, string s2) {
int m = s1.Length;
int n = s2.Length;
// dp array is initialized to all zeros
int[] dp = new int[n + 1];
// i and j represent the lengths of
// s1 and s2 respectively
for (int i = 1; i <= m; ++i) {
// prev stores the value from the previous
// row and previous column (i-1), (j -1)
int prev = dp[0];
for (int j = 1; j <= n; ++j) {
// temp temporarily stores the current
// dp[j] before it gets updated
int temp = dp[j];
if (s1[i - 1] == s2[j - 1]) {
// If characters match, add 1 to the value
// from the previous row and previous column
dp[j] = 1 + prev;
} else {
// Otherwise, take the maximum of the
// left and top values
dp[j] = Math.Max(dp[j - 1], dp[j]);
}
// Update prev for the next iteration
prev = temp;
}
}
// The last element of the array
// contains the length of the LCS
return dp[n];
}
static void Main() {
string s1 = "AGGTAB";
string s2 = "GXTXAYB";
int res = lcs(s1, s2);
Console.WriteLine(res);
}
}
JavaScript
// JavaScript program to find the longest common subsequence of two strings
// using space optimization
function lcs(s1, s2) {
const m = s1.length;
const n = s2.length;
// dp array is initialized to all zeros
const dp = Array(n + 1).fill(0);
// i and j represent the lengths of s1 and s2
// respectively
for (let i = 1; i <= m; ++i) {
// prev stores the value from the previous
// row and previous column (i-1), (j -1)
let prev = dp[0];
for (let j = 1; j <= n; ++j) {
// temp temporarily stores the current
// dp[j] before it gets updated
const temp = dp[j];
if (s1[i - 1] === s2[j - 1]) {
// If characters match, add 1 to the value
// from the previous row and previous column
dp[j] = 1 + prev;
}
else {
// Otherwise, take the maximum of the
// left and top values
dp[j] = Math.max(dp[j - 1], dp[j]);
}
// Update prev for the next iteration
prev = temp;
}
}
// The last element of the array
// contains the length of the LCS
return dp[n];
}
const s1 = "AGGTAB";
const s2 = "GXTXAYB";
const res = lcs(s1, s2);
console.log(res);
Similar Reads
Longest Common Subsequence (LCS) Given two strings, s1 and s2, the task is to find the length of the Longest Common Subsequence. If there is no common subsequence, return 0. A subsequence is a string generated from the original string by deleting 0 or more characters, without changing the relative order of the remaining characters.
15+ min read
Printing Longest Common Subsequence Given two sequences, print the longest subsequence present in both of them. Examples: LCS for input Sequences âABCDGHâ and âAEDFHRâ is âADHâ of length 3. LCS for input Sequences âAGGTABâ and âGXTXAYBâ is âGTABâ of length 4.We have discussed Longest Common Subsequence (LCS) problem in a previous post
15+ min read
Longest Common Subsequence | DP using Memoization Given two strings s1 and s2, the task is to find the length of the longest common subsequence present in both of them. Examples: Input: s1 = âABCDGHâ, s2 = âAEDFHRâ Output: 3 LCS for input Sequences âAGGTABâ and âGXTXAYBâ is âGTABâ of length 4. Input: s1 = âstriverâ, s2 = ârajâ Output: 1 The naive s
13 min read
Longest Common Increasing Subsequence (LCS + LIS) Given two arrays, a[] and b[], find the length of the longest common increasing subsequence(LCIS). LCIS refers to a subsequence that is present in both arrays and strictly increases.Prerequisites: LCS, LIS.Examples:Input: a[] = [3, 4, 9, 1], b[] = [5, 3, 8, 9, 10, 2, 1]Output: 2Explanation: The long
15+ min read
LCS (Longest Common Subsequence) of three strings Given three strings s1, s2 and s3. Your task is to find the longest common sub-sequence in all three given sequences.Note: This problem is simply an extension of LCS.Examples: Input: s1 = "geeks" , s2 = "geeksfor", s3 = "geeksforgeeks"Output : 5Explanation: Longest common subsequence is "geeks" i.e.
15+ min read
C++ Program for Longest Common Subsequence LCS Problem Statement: 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
3 min read
Java Program for Longest Common Subsequence LCS Problem Statement: 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
4 min read
Python Program for Longest Common Subsequence LCS Problem Statement: 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
3 min read
Problems on LCS
Edit distance and LCS (Longest Common Subsequence)In standard Edit Distance where we are allowed 3 operations, insert, delete, and replace. Consider a variation of edit distance where we are allowed only two operations insert and delete, find edit distance in this variation. Examples: Input : str1 = "cat", st2 = "cut"Output : 2We are allowed to ins
6 min read
Length of longest common subsequence containing vowelsGiven two strings X and Y of length m and n respectively. The problem is to find the length of the longest common subsequence of strings X and Y which contains all vowel characters.Examples: Input : X = "aieef" Y = "klaief"Output : aieInput : X = "geeksforgeeks" Y = "feroeeks"Output : eoeeSource:Pay
14 min read
Longest Common Subsequence (LCS) by repeatedly swapping characters of a string with characters of another stringGiven two strings A and B of lengths N and M respectively, the task is to find the length of the longest common subsequence that can be two strings if any character from string A can be swapped with any other character from B any number of times. Examples: Input: A = "abdeff", B = "abbet"Output: 4Ex
7 min read
Longest Common Subsequence with at most k changes allowedGiven two sequence P and Q of numbers. The task is to find Longest Common Subsequence of two sequences if we are allowed to change at most k element in first sequence to any value. Examples: Input : P = { 8, 3 } Q = { 1, 3 } K = 1 Output : 2 If we change first element of first sequence from 8 to 1,
8 min read
Minimum cost to make Longest Common Subsequence of length kGiven two string X, Y and an integer k. Now the task is to convert string X with the minimum cost such that the Longest Common Subsequence of X and Y after conversion is of length k. The cost of conversion is calculated as XOR of old character value and new character value. The character value of 'a
14 min read
Longest Common SubstringGiven two strings 's1' and 's2', find the length of the longest common substring. Example: Input: s1 = "GeeksforGeeks", s2 = "GeeksQuiz" Output : 5 Explanation:The longest common substring is "Geeks" and is of length 5.Input: s1 = "abcdxyz", s2 = "xyzabcd" Output : 4Explanation:The longest common su
15+ min read
Longest Common Subsequence of two arrays out of which one array consists of distinct elements onlyGiven two arrays firstArr[], consisting of distinct elements only, and secondArr[], the task is to find the length of LCS between these 2 arrays. Examples: Input: firstArr[] = {3, 5, 1, 8}, secondArr[] = {3, 3, 5, 3, 8}Output: 3.Explanation: LCS between these two arrays is {3, 5, 8}. Input : firstAr
7 min read
Longest Repeating SubsequenceGiven a string s, the task is to find the length of the longest repeating subsequence, such that the two subsequences don't have the same string character at the same position, i.e. any ith character in the two subsequences shouldn't have the same index in the original string. Examples:Input: s= "ab
15+ min read
Longest Common Anagram SubsequenceGiven two strings str1 and str2 of length n1 and n2 respectively. The problem is to find the length of the longest subsequence which is present in both the strings in the form of anagrams. Note: The strings contain only lowercase letters. Examples: Input : str1 = "abdacp", str2 = "ckamb" Output : 3
7 min read
Length of Longest Common Subsequence with given sum KGiven two arrays a[] and b[] and an integer K, the task is to find the length of the longest common subsequence such that sum of elements is equal to K. Examples: Input: a[] = { 9, 11, 2, 1, 6, 2, 7}, b[] = {1, 2, 6, 9, 2, 3, 11, 7}, K = 18Output: 3Explanation: Subsequence { 11, 7 } and { 9, 2, 7 }
15+ min read
Longest Common Subsequence with no repeating characterGiven two strings s1 and s2, the task is to find the length of the longest common subsequence with no repeating character. Examples: Input: s1= "aabbcc", s2= "aabc"Output: 3Explanation: "aabc" is longest common subsequence but it has two repeating character 'a'.So the required longest common subsequ
10 min read
Find the Longest Common Subsequence (LCS) in given K permutationsGiven K permutations of numbers from 1 to N in a 2D array arr[][]. The task is to find the longest common subsequence of these K permutations. Examples: Input: N = 4, K = 3arr[][] = {{1, 4, 2, 3}, {4, 1, 2, 3}, {1, 2, 4, 3}}Output: 3Explanation: Longest common subsequence is {1, 2, 3} which has leng
10 min read
Find length of longest subsequence of one string which is substring of another stringGiven two strings X and Y. The task is to find the length of the longest subsequence of string X which is a substring in sequence Y.Examples: Input : X = "ABCD", Y = "BACDBDCD"Output : 3Explanation: "ACD" is longest subsequence of X which is substring of Y.Input : X = "A", Y = "A"Output : 1Perquisit
15+ min read
Length of longest common prime subsequence from two given arraysGiven two arrays arr1[] and arr2[] of length N and M respectively, the task is to find the length of the longest common prime subsequence that can be obtained from the two given arrays. Examples: Input: arr1[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}, arr2[] = {2, 5, 6, 3, 7, 9, 8} Output: 4 Explanation: The l
11 min read
A Space Optimized Solution of LCSGiven two strings, s1 and s2, the task is to find the length of the Longest Common Subsequence. If there is no common subsequence, return 0.Examples:Input: s1 = âABCDGHâ, s2 = âAEDFHRâOutput: 3Explanation: The longest subsequence present in both strings is "ADH".Input: s1 = âAGGTABâ, s2 = âGXTXAYBâO
13 min read
Longest common subarray in the given two arraysGiven two arrays A[] and B[] of N and M integers respectively, the task is to find the maximum length of an equal subarray or the longest common subarray between the two given array. Examples: Input: A[] = {1, 2, 8, 2, 1}, B[] = {8, 2, 1, 4, 7} Output: 3 Explanation: The subarray that is common to b
15+ min read
Number of ways to insert a character to increase the LCS by oneGiven two strings A and B. The task is to count the number of ways to insert a character in string A to increase the length of the Longest Common Subsequence between string A and string B by 1. Examples: Input : A = "aa", B = "baaa" Output : 4 The longest common subsequence shared by string A and st
11 min read
Longest common subsequence with permutations allowedGiven two strings in lowercase, find the longest string whose permutations are subsequences of given two strings. The output longest string must be sorted. Examples: Input : str1 = "pink", str2 = "kite" Output : "ik" The string "ik" is the longest sorted string whose one permutation "ik" is subseque
7 min read
Longest subsequence such that adjacent elements have at least one common digitGiven an array arr[], the task is to find the length of the longest sub-sequence such that adjacent elements of the subsequence have at least one digit in common.Examples: Input: arr[] = [1, 12, 44, 29, 33, 96, 89] Output: 5 Explanation: The longest sub-sequence is [1 12 29 96 89]Input: arr[] = [12,
15+ min read
Longest subsequence with different adjacent charactersGiven string str. The task is to find the longest subsequence of str such that all the characters adjacent to each other in the subsequence are different. Examples:Â Â Input: str = "ababa"Â Output: 5Â Explanation:Â "ababa" is the subsequence satisfying the condition Input: str = "xxxxy"Â Output: 2Â Explan
14 min read
Longest subsequence such that difference between adjacents is oneGiven an array arr[] of size n, the task is to find the longest subsequence such that the absolute difference between adjacent elements is 1.Examples: Input: arr[] = [10, 9, 4, 5, 4, 8, 6]Output: 3Explanation: The three possible subsequences of length 3 are [10, 9, 8], [4, 5, 4], and [4, 5, 6], wher
15+ min read
Longest Uncommon SubsequenceGiven two strings, find the length of longest uncommon subsequence of the two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings which is not a subsequence of other strings. Examples: Input : "abcd", "abc"Output : 4The longest subsequence is 4 bec
12 min read
LCS formed by consecutive segments of at least length KGiven two strings s1, s2 and K, find the length of the longest subsequence formed by consecutive segments of at least length K. Examples: Input : s1 = aggayxysdfa s2 = aggajxaaasdfa k = 4 Output : 8 Explanation: aggasdfa is the longest subsequence that can be formed by taking consecutive segments, m
9 min read
Longest Increasing Subsequence using Longest Common Subsequence AlgorithmGiven an array arr[] of N integers, the task is to find and print the Longest Increasing Subsequence.Examples: Input: arr[] = {12, 34, 1, 5, 40, 80} Output: 4 {12, 34, 40, 80} and {1, 5, 40, 80} are the longest increasing subsequences.Input: arr[] = {10, 22, 9, 33, 21, 50, 41, 60, 80} Output: 6 Prer
12 min read