Related Articles

# Minimize elements to be added to a given array such that it contains another given array as its subsequence

• Difficulty Level : Easy
• Last Updated : 09 Jun, 2021

Given an array A[] consisting of N distinct integers and another array B[] consisting of M integers, the task is to find the minimum number of elements to be added to the array B[] such that the array A[] becomes the subsequence of the array B[].

Examples:

Input: N = 5, M = 6, A[] = {1, 2, 3, 4, 5}, B[] = {2, 5, 6, 4, 9, 12}
Output: 3
Explanation:
Below are the element that are needed to be added:
1) Add 1 before element 2 of B[]
2) Add 3 after element 6 of B[]
3) Add 5 in the last position of B[].
Therefore, the resulting array B[] is {1, 2, 5, 6, 3, 4, 9, 12, 5}.
Hence, A[] is the subsequence of B[] after adding 3 elements.

Input: N = 5, M = 5, A[] = {3, 4, 5, 2, 7}, B[] = {3, 4, 7, 9, 2}
Output:
Explanation:
Below are the elements that are needed to be added:
1) Add 5 after element 4.
2) Add 2 after element 5.
Therefore, the resulting array B[] is {3, 4, 5, 2, 7, 9, 2}.
Hence 2 elements are required to be added.

Naive Approach: The naive approach is to generate all the subsequences of the array B and then find that subsequence such that on adding a minimum number of elements from the array A to make it equal to the array A. Print the minimum count of element added.
Time Complexity: O(N*2M)
Auxiliary Space: O(M+N)

Efficient Approach: The above approach can be optimized using Dynamic Programming. The idea is to find the Longest Common Subsequence between the given two arrays A and B. The main observation is that the minimum number of elements to be added in B[] such that A[] becomes its subsequence can be found by subtracting the length of the longest common subsequence from the length of the array A[].

Therefore, the difference between the length of the array A[] and length of the Longest Common Subsequence is the required result.

Below is the implementation of the above approach:

## C++14

 `// C++14 program for the above approach``#include ``using` `namespace` `std;` `// Function that finds the minimum number``// of the element must be added to make A``// as a subsequence in B``int` `transformSubsequence(``int` `n, ``int` `m,``                         ``vector<``int``> A,``                         ``vector<``int``> B)``{``    ` `    ``// Base Case``    ``if` `(B.size() == 0)``        ``return` `n;` `    ``// dp[i][j] indicates the length of``    ``// LCS of A of length i & B of length j``    ``vector> dp(n + 1,``           ``vector<``int``>(m + 1, 0));` `    ``for``(``int` `i = 0; i < n + 1; i++)``    ``{``        ``for``(``int` `j = 0; j < m + 1; j++)``        ``{``            ` `            ``// If there are no elements``            ``// either in A or B then the``            ``// length of lcs is 0``            ``if` `(i == 0 or j == 0)``                ``dp[i][j] = 0;` `            ``// If the element present at``            ``// ith and jth index of A and B``            ``// are equal then include in LCS``            ``else` `if` `(A[i - 1] == B[j - 1])``                ``dp[i][j] = 1 + dp[i - 1][j - 1];` `            ``// If they are not equal then``            ``// take the max``            ``else``                ``dp[i][j] = max(dp[i - 1][j],``                               ``dp[i][j - 1]);``        ``}``    ``}` `    ``// Return difference of length``    ``// of A and lcs of A and B``    ``return` `n - dp[n][m];``}` `// Driver Code``int` `main()``{``    ``int` `N = 5;``    ``int` `M = 6;` `    ``// Given sequence A and B``    ``vector<``int``> A = { 1, 2, 3, 4, 5 };``    ``vector<``int``> B = { 2, 5, 6, 4, 9, 12 };` `    ``// Function call``    ``cout << transformSubsequence(N, M, A, B);` `    ``return` `0;``}` `// This code is contributed by mohit kumar 29`

## Java

 `// Java program for``// the above approach``import` `java.util.*;``class` `GFG{` `// Function that finds the minimum number``// of the element must be added to make A``// as a subsequence in B``static` `int` `transformSubsequence(``int` `n, ``int` `m,``                                ``int` `[]A, ``int` `[]B)``{``  ``// Base Case``  ``if` `(B.length == ``0``)``    ``return` `n;` `  ``// dp[i][j] indicates the length of``  ``// LCS of A of length i & B of length j``  ``int` `[][]dp = ``new` `int``[n + ``1``][m + ``1``];` `  ``for``(``int` `i = ``0``; i < n + ``1``; i++)``  ``{``    ``for``(``int` `j = ``0``; j < m + ``1``; j++)``    ``{``      ``// If there are no elements``      ``// either in A or B then the``      ``// length of lcs is 0``      ``if` `(i == ``0` `|| j == ``0``)``        ``dp[i][j] = ``0``;` `      ``// If the element present at``      ``// ith and jth index of A and B``      ``// are equal then include in LCS``      ``else` `if` `(A[i - ``1``] == B[j - ``1``])``        ``dp[i][j] = ``1` `+ dp[i - ``1``][j - ``1``];` `      ``// If they are not equal then``      ``// take the max``      ``else``        ``dp[i][j] = Math.max(dp[i - ``1``][j],``                            ``dp[i][j - ``1``]);``    ``}``  ``}` `  ``// Return difference of length``  ``// of A and lcs of A and B``  ``return` `n - dp[n][m];``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``  ``int` `N = ``5``;``  ``int` `M = ``6``;` `  ``// Given sequence A and B``  ``int` `[]A = {``1``, ``2``, ``3``, ``4``, ``5``};``  ``int` `[]B = {``2``, ``5``, ``6``, ``4``, ``9``, ``12``};` `  ``// Function call``  ``System.out.print(transformSubsequence(N, M, A, B));``}``}` `// This code is contributed by 29AjayKumar`

## Python3

 `# Python3 program for the above approach` `# Function that finds the minimum number``# of the element must be added to make A``# as a subsequence in B``def` `transformSubsequence(n, m, A, B):` `    ``# Base Case``    ``if` `B ``is` `None` `or` `len``(B) ``=``=` `0``:``        ``return` `n` `    ``# dp[i][j] indicates the length of``    ``# LCS of A of length i & B of length j``    ``dp ``=` `[[``0` `for` `col ``in` `range``(m ``+` `1``)]``        ``for` `row ``in` `range``(n ``+` `1``)]` `    ``for` `i ``in` `range``(n ``+` `1``):` `        ``for` `j ``in` `range``(m ``+` `1``):` `            ``# If there are no elements``            ``# either in A or B then the``            ``# length of lcs is 0``            ``if` `i ``=``=` `0` `or` `j ``=``=` `0``:``                ``dp[i][j] ``=` `0` `            ``# If the element present at``            ``# ith and jth index of A and B``            ``# are equal then include in LCS``            ``elif` `A[i``-``1``] ``=``=` `B[j``-``1``]:``                ``dp[i][j] ``=` `1` `+` `dp[i``-``1``][j``-``1``]` `            ``# If they are not equal then``            ``# take the max``            ``else``:``                ``dp[i][j] ``=` `max``(dp[i``-``1``][j], dp[i][j``-``1``])` `    ``# Return difference of length``    ``# of A and lcs of A and B``    ``return` `n ``-` `dp[n][m]`  `# Driver Code``if` `__name__ ``=``=` `"__main__"``:` `    ``N ``=` `5``    ``M ``=` `6``    ` `    ``# Given Sequence A and B``    ``A ``=` `[``1``, ``2``, ``3``, ``4``, ``5``]``    ``B ``=` `[``2``, ``5``, ``6``, ``4``, ``9``, ``12``]` `    ``# Function Call``    ``print``(transformSubsequence(N, M, A, B))`

## C#

 `// C# program for``// the above approach``using` `System;``class` `GFG{` `// Function that finds the minimum number``// of the element must be added to make A``// as a subsequence in B``static` `int` `transformSubsequence(``int` `n, ``int` `m,``                                ``int` `[]A, ``int` `[]B)``{``  ``// Base Case``  ``if` `(B.Length == 0)``    ``return` `n;` `  ``// dp[i,j] indicates the length of``  ``// LCS of A of length i & B of length j``  ``int` `[,]dp = ``new` `int``[n + 1, m + 1];` `  ``for``(``int` `i = 0; i < n + 1; i++)``  ``{``    ``for``(``int` `j = 0; j < m + 1; j++)``    ``{``      ``// If there are no elements``      ``// either in A or B then the``      ``// length of lcs is 0``      ``if` `(i == 0 || j == 0)``        ``dp[i, j] = 0;` `      ``// If the element present at``      ``// ith and jth index of A and B``      ``// are equal then include in LCS``      ``else` `if` `(A[i - 1] == B[j - 1])``        ``dp[i, j] = 1 + dp[i - 1, j - 1];` `      ``// If they are not equal then``      ``// take the max``      ``else``        ``dp[i, j] = Math.Max(dp[i - 1, j],``                            ``dp[i, j - 1]);``    ``}``  ``}` `  ``// Return difference of length``  ``// of A and lcs of A and B``  ``return` `n - dp[n, m];``}` `// Driver Code``public` `static` `void` `Main(String[] args)``{``  ``int` `N = 5;``  ``int` `M = 6;` `  ``// Given sequence A and B``  ``int` `[]A = {1, 2, 3, 4, 5};``  ``int` `[]B = {2, 5, 6, 4, 9, 12};` `  ``// Function call``  ``Console.Write(transformSubsequence(N, M,``                                     ``A, B));``}``}` `// This code is contributed by Rajput-Ji`

## Javascript

 ``
Output:
`3`

Time Complexity: O(M*M), where N and M are the lengths of array A[] and B[] respectively.
Auxiliary Space: O(M*N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up