The Wayback Machine - https://web.archive.org/web/20240819014721/https://www.geeksforgeeks.org/minimum-cost-make-longest-common-subsequence-length-k/
Open In App

Minimum cost to make Longest Common Subsequence of length k

Last Updated : 23 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given 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’ is 0, ‘b’ is 1, and so on.

Examples: 

Input : X = "abble", 
Y = "pie",
k = 2
Output : 25

If you changed 'a' to 'z', it will cost 0 XOR 25.

The problem can be solved by slight change in Dynamic Programming problem of Longest Increasing Subsequence. Instead of two states, we maintain three states. 
Note, that if k > min(n, m) then it’s impossible to attain LCS of atleast k length, else it’s always possible. 
Let dp[i][j][p] stores the minimum cost to achieve LCS of length p in x[0…i] and y[0….j]. 
With base step as dp[i][j][0] = 0 because we can achieve LCS of 0 length without any cost and for i < 0 or j 0 in such case). 
Else there are 3 cases: 
1. Convert x[i] to y[j]. 
2. Skip ith character from x. 
3. Skip jth character from y.

If we convert x[i] to y[j], then cost = f(x[i]) XOR f(y[j]) will be added and LCS will decrease by 1. f(x) will return the character value of x. 
Note that the minimum cost to convert a character ‘a’ to any character ‘c’ is always f(a) XOR f(c) because f(a) XOR f(c) <= (f(a) XOR f(b) + f(b) XOR f(c)) for all a, b, c. 
If you skip ith character from x then i will be decreased by 1, no cost will be added and LCS will remain the same. 
If you skip jth character from x then j will be decreased by 1, no cost will be added and LCS will remain the same.

Therefore,

dp[i][j][k] = min(cost + dp[i - 1][j - 1][k - 1], 
dp[i - 1][j][k],
dp[i][j - 1][k])
The minimum cost to make the length of their
LCS atleast k is dp[n - 1][m - 1][k]

C++




#include <bits/stdc++.h>
using namespace std;
const int N = 30;
 
// Return Minimum cost to make LCS of length k
int solve(char X[], char Y[], int l, int r,
                     int k, int dp[][N][N])
{
    // If k is 0.
    if (!k)
        return 0;
 
    // If length become less than 0, return
    // big number.
    if (l < 0 | r < 0)
        return 1e9;
 
    // If state already calculated.
    if (dp[l][r][k] != -1)
        return dp[l][r][k];
 
    // Finding the cost
    int cost = (X[l] - 'a') ^ (Y[r] - 'a');
 
    // Finding minimum cost and saving the state value
    return dp[l][r][k] = min({cost +
                      solve(X, Y, l - 1, r - 1, k - 1, dp),
                             solve(X, Y, l - 1, r, k, dp),
                             solve(X, Y, l, r - 1, k, dp)});
}
 
// Driven Program
int main()
{
    char X[] = "abble";
    char Y[] = "pie";
    int n = strlen(X);
    int m = strlen(Y);
    int k = 2;
 
    int dp[N][N][N];
    memset(dp, -1, sizeof dp);
    int ans = solve(X, Y, n - 1, m - 1, k, dp);
 
    cout << (ans == 1e9 ? -1 : ans) << endl;
    return 0;
}


Java




import java.util.*;
import java.io.*;
 
class GFG
{
 
    static int N = 30;
 
    // Return Minimum cost to make LCS of length k
    static int solve(char X[], char Y[], int l, int r,
                                    int k, int dp[][][])
    {
        // If k is 0.
        if (k == 0)
        {
            return 0;
        }
 
        // If length become less than 0, return
        // big number.
        if (l < 0 | r < 0)
        {
            return (int) 1e9;
        }
 
        // If state already calculated.
        if (dp[l][r][k] != -1)
        {
            return dp[l][r][k];
        }
 
        // Finding the cost
        int cost = (X[l] - 'a') ^ (Y[r] - 'a');
 
        // Finding minimum cost and saving the state value
        return dp[l][r][k] = Math.min(Math.min(cost +
                solve(X, Y, l - 1, r - 1, k - 1, dp),
                solve(X, Y, l - 1, r, k, dp)),
                solve(X, Y, l, r - 1, k, dp));
    }
 
    // Driver code
    public static void main(String[] args)
    {
        char X[] = "abble".toCharArray();
        char Y[] = "pie".toCharArray();
        int n = X.length;
        int m = Y.length;
        int k = 2;
 
        int[][][] dp = new int[N][N][N];
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < N; j++)
            {
                for (int l = 0; l < N; l++)
                {
                    dp[i][j][l] = -1;
                }
            }
        }
        int ans = solve(X, Y, n - 1, m - 1, k, dp);
 
        System.out.println(ans == 1e9 ? -1 : ans);
    }
}
 
// This code contributed by Rajput-Ji


Python3




# Python3 program to calculate Minimum cost
# to make Longest Common Subsequence of length k
N = 30
 
# Return Minimum cost to make LCS of length k
def solve(X, Y, l, r, k, dp):
 
    # If k is 0
    if k == 0:
        return 0
 
    # If length become less than 0,
    # return big number
    if l < 0 or r < 0:
        return 1000000000
 
    # If state already calculated
    if dp[l][r][k] != -1:
        return dp[l][r][k]
 
    # Finding cost
    cost = ((ord(X[l]) - ord('a')) ^
            (ord(Y[r]) - ord('a')))
 
    dp[l][r][k] = min([cost + solve(X, Y, l - 1,
                                          r - 1, k - 1, dp),
                              solve(X, Y, l - 1, r, k, dp),
                              solve(X, Y, l, r - 1, k, dp)])
 
    return dp[l][r][k]
 
# Driver Code
if __name__ == "__main__":
    X = "abble"
    Y = "pie"
    n = len(X)
    m = len(Y)
    k = 2
    dp = [[[-1] * N for __ in range(N)]
                    for ___ in range(N)]
    ans = solve(X, Y, n - 1, m - 1, k, dp)
 
    print(-1 if ans == 1000000000 else ans)
 
# This code is contributed
# by vibhu4agarwal


C#




// C# program to find subarray with
// sum closest to 0
using System;
     
class GFG
{
 
    static int N = 30;
 
    // Return Minimum cost to make LCS of length k
    static int solve(char []X, char []Y, int l, int r,
                                    int k, int [,,]dp)
    {
        // If k is 0.
        if (k == 0)
        {
            return 0;
        }
 
        // If length become less than 0, return
        // big number.
        if (l < 0 | r < 0)
        {
            return (int) 1e9;
        }
 
        // If state already calculated.
        if (dp[l,r,k] != -1)
        {
            return dp[l,r,k];
        }
 
        // Finding the cost
        int cost = (X[l] - 'a') ^ (Y[r] - 'a');
 
        // Finding minimum cost and saving the state value
        return dp[l,r,k] = Math.Min(Math.Min(cost +
                solve(X, Y, l - 1, r - 1, k - 1, dp),
                solve(X, Y, l - 1, r, k, dp)),
                solve(X, Y, l, r - 1, k, dp));
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        char []X = "abble".ToCharArray();
        char []Y = "pie".ToCharArray();
        int n = X.Length;
        int m = Y.Length;
        int k = 2;
 
        int[,,] dp = new int[N, N, N];
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < N; j++)
            {
                for (int l = 0; l < N; l++)
                {
                    dp[i,j,l] = -1;
                }
            }
        }
        int ans = solve(X, Y, n - 1, m - 1, k, dp);
 
        Console.WriteLine(ans == 1e9 ? -1 : ans);
    }
}
 
// This code is contributed by Princi Singh


Javascript




<script>
 
// JavaScript program to calculate Minimum cost
// to make Longest Common Subsequence of length k
const N = 30
 
// Return Minimum cost to make LCS of length k
function solve(X, Y, l, r, k, dp){
 
    // If k is 0
    if(k == 0)
        return 0
 
    // If length become less than 0,
    // return big number
    if(l < 0 || r < 0)
        return 1000000000
 
    // If state already calculated
    if(dp[l][r][k] != -1)
        return dp[l][r][k]
 
    // Finding cost
    let cost = ((X[l].charCodeAt(0) - 'a'.charCodeAt(0)) ^ (Y[r].charCodeAt(0) - 'a'.charCodeAt(0)))
 
    dp[l][r][k] = Math.min(Math.min(cost + solve(X, Y, l - 1, r - 1, k - 1, dp),solve(X, Y, l - 1, r, k, dp)),
                              solve(X, Y, l, r - 1, k, dp))
 
    return dp[l][r][k]
}
 
// Driver Code
 
let X = "abble"
let Y = "pie"
let n = X.length
let m = Y.length
let k = 2
let dp = new Array(N);
for(let i = 0; i < N; i++)
{
    dp[i] = new Array(N);
    for(let j = 0; j < N; j++)
    {
        dp[i][j] = new Array(N).fill(-1);
    }
}
let ans = solve(X, Y, n - 1, m - 1, k, dp)
 
document.write((ans == 1000000000)? -1:ans)
 
// This code is contributed by shinjanpatra
 
</script>


Output

3




Time Complexity: O(n3)
Auxiliary Space: O(n3)

Efficient approach: Using DP Tabulation method ( Iterative approach )

The approach to solve this problem is same but DP tabulation(bottom-up) method is better then Dp + memoization(top-down) because memoization method needs extra stack space of recursion calls.

Steps to solve this problem :

  • Create a 3d DP to store the solution of the subproblems.
  • Initialize the DP with base cases when k= 0 dp value is 0 and when n=0 or m=0 dp value is 1e9 and dp[0][0][0] = 0 .
  • Now Iterate over subproblems to get the value of current problem form previous computation of subproblems stored in DP
  • Return the final solution stored in dp[n][m][k].

Implementation :

C++




// C++ code for above approach
 
#include <bits/stdc++.h>
using namespace std;
const int N = 30;
 
// Return Minimum cost to make LCS of length k
int solve(char X[], char Y[], int n, int m, int k)
{
    // Create 3D DP
    int dp[n + 1][m + 1][k + 1];
 
    // initialize DP with base cases
    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= m; j++) {
            for (int p = 0; p <= k; p++) {
                if (k == 0) {
                    dp[i][j][p] = 0;
                }
                else if (i == 0 || j == 0) {
                    dp[i][j][p] = 1e9;
                }
            }
        }
    }
 
    dp[0][0][0] = 0;
 
    // iterate over subproblem to get the current
    // value from previous computation store in DP
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            for (int p = 1; p <= k; p++) {
                int cost
                    = (X[i - 1] - 'a') ^ (Y[j - 1] - 'a');
 
                // update DP
                dp[i][j][p] = min(
                    { cost + dp[i - 1][j - 1][p - 1],
                      dp[i - 1][j][p], dp[i][j - 1][p] });
            }
        }
    }
 
    // return final answer
    return dp[n][m][k];
}
 
// Driven Program
int main()
{
    char X[] = "abble";
    char Y[] = "pie";
    int n = strlen(X);
    int m = strlen(Y);
    int k = 2;
 
    // function call
    int ans = solve(X, Y, n, m, k);
 
    cout << (ans == 1e9 ? -1 : ans) << endl;
    return 0;
}


Java




import java.util.*;
public class Main {
    public static int solve(char X[], char Y[], int n, int m, int k) {
        // Create 3D DP
        int dp[][][] = new int[n + 1][m + 1][k + 1];
        // initialize DP with base cases
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= m; j++) {
                for (int p = 0; p <= k; p++) {
                    if (k == 0) {
                        dp[i][j][p] = 0;
                    } else if (i == 0 || j == 0) {
                        dp[i][j][p] = Integer.MAX_VALUE / 2;
                    }
                }
            }
        }
        dp[0][0][0] = 0;
        // iterate over subproblem to get the current
        // value from previous computation store in DP
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                for (int p = 1; p <= k; p++) {
                    int cost = (X[i - 1]-'a') ^ (Y[j - 1]-'a');
                    // update DP
                    dp[i][j][p] = Math.min(Math.min(dp[i - 1][j - 1][p - 1] + cost, dp[i - 1][j][p]), dp[i][j - 1][p]);
                }
            }
        }
        // return final answer
        return dp[n][m][k];
    }
    // Driven Program
    public static void main(String[] args) {
        char X[] = "abble".toCharArray();
        char Y[] = "pie".toCharArray();
        int n = X.length;
        int m = Y.length;
        int k = 2;
        // function call
        int ans = solve(X, Y, n, m, k);
        System.out.println(ans);
    }
}


Python3




INF = float('inf')
 
# Return Minimum cost to make LCS of length k
 
 
def solve(X, Y, n, m, k):
    # Create 3D DP
    dp = [[[0 for p in range(k+1)] for j in range(m+1)] for i in range(n+1)]
 
    # initialize DP with base cases
    for i in range(n+1):
        for j in range(m+1):
            for p in range(k+1):
                if k == 0:
                    dp[i][j][p] = 0
                elif i == 0 or j == 0:
                    dp[i][j][p] = INF
 
    dp[0][0][0] = 0
 
    # iterate over subproblem to get the current
    # value from previous computation store in DP
    for i in range(1, n+1):
        for j in range(1, m+1):
            for p in range(1, k+1):
                cost = ord(X[i-1]) - ord('a') ^ ord(Y[j-1]) - ord('a')
 
                # update DP
                dp[i][j][p] = min(cost + dp[i-1][j-1][p-1],
                                  dp[i-1][j][p], dp[i][j-1][p])
 
    # return final answer
    return -1 if dp[n][m][k] == INF else dp[n][m][k]
 
 
# Driven Program
if __name__ == '__main__':
    X = "abble"
    Y = "pie"
    n = len(X)
    m = len(Y)
    k = 2
 
    # function call
    ans = solve(X, Y, n, m, k)
 
    print(ans)


C#




using System;
 
public class Program
{
    public static int Solve(char[] X, char[] Y, int n, int m, int k)
    {
        // Create 3D DP
        int[][][] dp = new int[n + 1][][];
 
        for (int i = 0; i <= n; i++)
        {
            dp[i] = new int[m + 1][];
            for (int j = 0; j <= m; j++)
            {
                dp[i][j] = new int[k + 1];
                for (int p = 0; p <= k; p++)
                {
                    if (k == 0)
                    {
                        dp[i][j][p] = 0;
                    }
                    else if (i == 0 || j == 0)
                    {
                        dp[i][j][p] = int.MaxValue / 2;
                    }
                }
            }
        }
 
        dp[0][0][0] = 0;
 
        // iterate over subproblem to get the current
        // value from previous computation store in DP
        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= m; j++)
            {
                for (int p = 1; p <= k; p++)
                {
                    int cost = (X[i - 1] - 'a') ^ (Y[j - 1] - 'a');
                    // update DP
                    dp[i][j][p] = Math.Min(
                        Math.Min(dp[i - 1][j - 1][p - 1] + cost, dp[i - 1][j][p]),
                        dp[i][j - 1][p]);
                }
            }
        }
 
        // return final answer
        return dp[n][m][k];
    }
 
    // Entry point of the program
    public static void Main(string[] args)
    {
        char[] X = "abble".ToCharArray();
        char[] Y = "pie".ToCharArray();
        int n = X.Length;
        int m = Y.Length;
        int k = 2;
        // function call
        int ans = Solve(X, Y, n, m, k);
        Console.WriteLine(ans);
    }
}


Javascript




const N = 30;
 
// Return Minimum cost to make LCS of length k
function solve(X, Y, n, m, k) {
    // Create 3D DP
    const dp = new Array(n + 1).fill(null)
        .map(() => new Array(m + 1).fill(null)
            .map(() => new Array(k + 1).fill(0)));
 
    // initialize DP with base cases
    for (let i = 0; i <= n; i++) {
        for (let j = 0; j <= m; j++) {
            for (let p = 0; p <= k; p++) {
                if (k === 0) {
                    dp[i][j][p] = 0;
                } else if (i === 0 || j === 0) {
                    dp[i][j][p] = Infinity;
                }
            }
        }
    }
 
    dp[0][0][0] = 0;
 
    // iterate over subproblem to get the current
    // value from previous computation store in DP
    for (let i = 1; i <= n; i++) {
        for (let j = 1; j <= m; j++) {
            for (let p = 1; p <= k; p++) {
                const cost = (X[i - 1].charCodeAt() - 'a'.charCodeAt()) ^
                    (Y[j - 1].charCodeAt() - 'a'.charCodeAt());
 
                // update DP
                dp[i][j][p] = Math.min(
                    cost + dp[i - 1][j - 1][p - 1],
                    dp[i - 1][j][p],
                    dp[i][j - 1][p]);
            }
        }
    }
 
    // return final answer
    return dp[n][m][k];
}
 
// Driven Program
const X = "abble";
const Y = "pie";
const n = X.length;
const m = Y.length;
const k = 2;
 
// function call
const ans = solve(X, Y, n, m, k);
 
console.log(ans === Infinity ? -1 : ans);


Output

3




Time Complexity: O(n*m*k)
Auxiliary Space: O(n*m*k)



Previous Article
Next Article

Similar Reads

Longest Increasing Subsequence using Longest Common Subsequence Algorithm
Given 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 Prerequisite: LCS, LISApproach: The longest increasing
12 min read
Maximum length subsequence such that adjacent elements in the subsequence have a common factor
Given an array arr[], the task is to find the maximum length of a subsequence such that the adjacent elements in the subsequence have a common factor. Examples: Input: arr[] = { 13, 2, 8, 6, 3, 1, 9 } Output: 5Max length subsequence with satisfied conditions: { 2, 8, 6, 3, 9 } Input: arr[] = { 12, 2, 8, 6, 3, 1, 9 } Output: 6Max length subsequence
9 min read
Length of longest common subsequence containing vowels
Given 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 : eoeeRecommended: Please try your approach on {IDE} first, befor
14 min read
Length of longest common prime subsequence from two given arrays
Given 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 longest common prime subsequence present in both th
11 min read
Length of Longest Common Subsequence with given sum K
Given 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 } has sum equal to 18. Among them { 9, 2, 7 } is lon
15+ min read
Make Longest Common Subsequence at least K
Given two strings A of length N and B of length M. These strings contain lowercase English alphabets. You are also given an integer K. You can change the character of x of string A to any other character y. The cost of this conversion is abs(ASCII(x)- ASCII(y)). Find the minimum cost required such that the length of the Longest Common Subsequence (
9 min read
Minimum cost for constructing the subsequence of length K from given string S
Given a string S consisting of N lowercase English alphabets, and an integer K and, an array cost[] of size 26 denoting the cost of each lowercase English alphabet, the task is to find the minimum cost to construct a subsequence of length K from the characters of the string S. Examples: Input: S = "aabcbc", K = 3, cost[] = {2, 1, 3, 9, 9, 9, 9, 9,
11 min read
Minimum cost to make a string free of a subsequence
Given string str consisting of lowercase English alphabets and an array of positive integer arr[] both of the same length. The task is to remove some characters from the given string such that no sub-sequence in the string forms the string "code". Cost of removing a character str[i] is arr[i]. Find the minimum cost to achieve the target. Examples:
6 min read
Length of longest Palindromic Subsequence of even length with no two adjacent characters same
Given a string str, the task is to find the length of the longest palindromic subsequence of even length with no two adjacent characters same except the middle characters. Examples: Input: str = "abscrcdba" Output: 6 Explanation: abccba is the required string which has no two consecutive characters same except the middle characters. Hence the lengt
11 min read
Length of longest subsequence whose difference between maximum and minimum ASCII value of characters is exactly one
Given a string S consisting of lowercase English alphabets, the task is to find the length of the longest subsequence from the given string such that the difference between the largest and smallest ASCII value is exactly 1. Examples: Input: S = "acbbebcg"Output: 5Explanation: The longest subsequence of required type is "cbbbc", whose length is 5.Th
6 min read
Longest Common Anagram Subsequence
Given 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 Subsequence of str1 = abc Subsequence of str2 = ca
7 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 solution for this problem is to generate all subseq
13 min read
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 : 2 We are allowed to insert and delete. We delete 'a' from "cat" and ins
6 min read
Longest Subsequence with at least one common digit in every element
Given an array. The task is to find the length of the longest subsequence in which all elements must have at least one digit in common. Examples: Input : arr[] = { 11, 12, 23, 74, 13 } Output : 3 Explanation: The elements 11, 12, and 13 have the digit '1' as common. So it is the required longest sub-sequence. Input : arr[] = { 12, 90, 67, 78, 45 }
9 min read
Longest Common Subsequence of two arrays out of which one array consists of distinct elements only
Given 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 : firstArr[] = {1, 2, 1}, secondArr[] = {3}Output: 0 Naive
7 min read
Longest Common Subsequence (LCS) by repeatedly swapping characters of a string with characters of another string
Given 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: 4Explanation: Swapping A[5] and B[4] modifies A to "a
7 min read
Find the Longest Common Subsequence (LCS) in given K permutations
Given 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 length 3. Input: N = 6, K = 3,arr[][] = {{2, 5, 1, 4,
10 min read
Longest Common Subsequence with no repeating character
Given 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 subsequence with no repeating character is "abc". Input:
10 min read
Longest subsequence such that adjacent elements have at least one common digit
Given an array arr[] of N integers, the task is to find the length of the longest sub-sequence such that adjacent elements of the sub-sequence have at least one digit in common.Examples: Input: arr[] = {1, 12, 44, 29, 33, 96, 89} Output: 5 The longest sub-sequence is {1 12 29 96 89}Input: arr[] = {12, 23, 45, 43, 36, 97} Output: 4 The longest sub-s
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. The function discussed there was mainly to find
15+ min read
Longest common anagram subsequence from N strings
Given N strings. Find the longest possible subsequence from each of these N strings such that they are anagram to each other. The task is to print the lexicographically largest subsequence among all the subsequences. Examples: Input: s[] = { geeks, esrka, efrsk } Output: ske First string has "eks", Second string has "esk", third string has "esk". T
11 min read
Longest Common Increasing Subsequence (LCS + LIS)
Prerequisites : LCS, LIS Given two arrays, find length of the longest common increasing subsequence [LCIS] and print one of such sequences (multiple sequences may exist)Suppose we consider two arrays - arr1[] = {3, 4, 9, 1} and arr2[] = {5, 3, 8, 9, 10, 2, 1}Our answer would be {3, 9} as this is the longest common subsequence which is increasing al
15+ min read
Printing Longest Common Subsequence | Set 2 (Printing All)
Given two sequences, print all longest subsequence present in both of them.Examples: Input: string X = "AGTGATG" string Y = "GTTAG" Output: GTAG GTTG Input: string X = "AATCC" string Y = "ACACG" Output: ACC AAC Input: string X = "ABCBDAB" string Y = "BDCABA" Output: BCAB BCBA BDAB We have discussed Longest Common Subsequence (LCS) problem here. The
12 min read
Longest common subsequence with permutations allowed
Given 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 subsequence of "pink" and another permutation "ki" is subs
7 min read
LCS (Longest Common Subsequence) of three strings
Given 3 strings of all having length &lt; 100,the task is to find the longest common sub-sequence in all three given sequences. Examples: Input : str1 = "geeks" str2 = "geeksfor" str3 = "geeksforgeeks" Output : 5 Longest common subsequence is "geeks" i.e., length = 5 Input : str1 = "abcd1e2" str2 = "bc12ea" str3 = "bd1ea" Output : 3 Longest common
13 min read
Longest Common Subsequence with at most k changes allowed
Given 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, both sequences become same. Input : P = { 1, 2, 3,
8 min read
Longest Common Subsequence (LCS)
Given two strings, S1 and S2, the task is to find the length of the Longest Common Subsequence, i.e. longest subsequence present in both of the strings. If there is no common subsequence, return 0. A subsequence is a string generated from the original string with some characters (can be none) deleted without changing the relative order of the remai
15+ min read
Longest Subsequence with absolute difference of pairs as at least Subsequence's maximum
Given an array arr[] of length N. The task is to find the length of the longest subsequence of the array such that the absolute difference between any pair of elements is greater than or equal to the maximum element in that subsequence. Examples: Input: N = 6, arr[] = {1, 1, 0, 0, 0, 0}Output: 4Explanation: Considering 0 as max element of subsequen
7 min read
Longest subsequence such that every element in the subsequence is formed by multiplying previous element with a prime
Given a sorted array of N integers. The task is to find the longest subsequence such that every element in the subsequence is reachable by multiplying any prime number to the previous element in the subsequence.Note: A[i] &lt;= 105 Examples: Input: a[] = {3, 5, 6, 12, 15, 36} Output 4 The longest subsequence is {3, 6, 12, 36} 6 = 3*2 12 = 6*2 36 =
15+ min read
Minimum cost to convert all elements of a K-size subarray to 0 from given Ternary Array with subarray sum as cost
Given an array arr[] of N integers, where each array element is either 0, 1, or 2, and an integer K, the task is to print the minimum cost needed to convert all the elements of the array to 0s by selecting a subarray of size K and converting any array element of the subarray to 0 in one operation with the cost equal to the sum of elements of the su
11 min read
three90RightbarBannerImg