VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimize-elements-to-be-added-to-a-given-array-such-that-it-contains-another-given-array-as-its-subsequence-set-2/

⇱ Minimize elements to be added to a given array such that it contains another given array as its subsequence | Set 2 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 15 Jul, 2025

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 elements that need 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 need 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: Refer to the previous post of this article for the simplest approach to solve the problem. 

Time Complexity: O(N * 2M)
Auxiliary Space: O(M + N)

Dynamic Programming Approach: Refer to the previous post of this article for the Longest Common Subsequence based approach. 

Time Complexity: O(N * M)
Auxiliary Space: O(N * M)

Efficient Approach: The idea is similar to finding the Longest Increasing Subsequence(LIS) from the array B[]. Follow the steps below to solve the problem:

  • Consider elements of array B[] which are present in the array A[], and store the indices of each element of the array A[] in a Map
  • Then, find the LIS array subseq[] using Binary Search which consists of the indices in increasing order.
  • Finally, the minimum number of elements to be inserted into array B[] is equal to N - len(LIS), where len(LIS) is calculated using Binary Search in the above steps.

Below is the implementation of the above approach:


Output: 
3

 

Time Complexity: O(N logN)
Auxiliary Space: O(N)

Comment