VOOZH about

URL: https://www.geeksforgeeks.org/dsa/make-longest-common-subsequence-at-least-k/

⇱ Make Longest Common Subsequence at least K - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Make Longest Common Subsequence at least K

Last Updated : 23 Jul, 2025

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 (LCS) of A and B is at least K.

Constraints:

  • 1 <= N <= 100
  • 1 <= M <= 100

Examples:

Input: N = 5, M = 4, K = 3, A = "abcba", B = "acyx"
Output: 22
Explanation: As the minimum length of the subsequences is 3, we have to match any 3 characters of A with B. We can convert A[3] to "x" with cost = 22, then we can get the Longest Common Subsequence as "acx" of length 3.

Input: N = 3, M = 3, K = 3, A = "abc", B = "abc"
Output: 0
Explanation: As the minimum length is 3 both the string is of length 3 and every character is matches no change is needed and the minimum cost will be 0.

Approach: To solve the problem follow the below idea

The problem can be solved using Dynamic Programming. We can make a recursive function rec(i1, i2, K) which returns the minimum cost to have a Longest Common Subsequence of length K if we are at index i1 in string A and index i2 in string B. For any function rec(i1, i2, K) we have 3 choices:

  • Skip the i1th character of A, cost = rec(i1 - 1, i2, K)
  • Skip the i2th character of B, cost = rec(i1, i2 - 1, K)
  • Include the i1th character of A and i2th character of B for LCS with cost = abs(A[i1] - B[i2]) + rec(i1 - 1, i2 - 1, K - 1)

Use a 3D array dp[N][M][K] for memoization. Iterate for each N, M and K get the minimum cost.

Below are the steps to solve this problem:

  • As maximum length can be 100, Initialize a 3D dp of size [105] [105] [105] filled with -1.
  • If characters present at index M -1 and N -1 are equal, we need 0 cost.
  • Otherwise, get the absolute difference of characters A[n] and B[m] and add it as cost.
  • Look for the minimum cost from { rec(A, B, n - 1, m, k), x + rec(A, B, n - 1, m - 1, k - 1), rec(A, B, n, m - 1, k) }. And proceed further with it.
  • Return the dp[n][m][k] as the minimum cost.

Below is the implementation of the code:


Output
22

Time Complexity: O(N * M * K), where N is the length of string A and M is the length of string B.
Auxiliary Space: O(N * M * K)

Comment