Minimum operations to convert array A to B | Practice | GeeksforGeeks

Given two Arrays A[] and B[] of length N and M respectively. Find the minimum number of insertions and deletions on the array A[], required to make both the arrays identical.
Note: Array B[] is sorted and all its elements are distinct, operations can be performed at any index not necessarily at end.
 
Example 1:
Input:
N = 5, M = 3
A[] = {1, 2, 5, 3, 1}
B[] = {1, 3, 5}
Output:
4
Explanation:
We need to delete 2 and replace it with 3.
This costs 2 steps. Further, we will have to
delete the last two elements from A to
obtain an identical array to B. Overall, it
results in 4 steps.

Input:
N = 2, M = 2
A[] = {1, 4}
B[] = {1, 4}
Output :
0
Explanation:
Both the Arrays are already identical.


Your Task:  
You don't need to read input or print anything. Your task is to complete the function minInsAndDel() which takes two integers N and M, and two arrays A of size N and B of size M respectively as input and returns the minimum insertions and deletions required.

Expected Time Complexity: O(NlogN)
Expected Auxiliary Space: O(N)

Constraints:
1 ≤ N ≤ 105
1 ≤ A[i], B[i] ≤ 105
0
beheraalokmaya2 weeks ago
hi this is the converting
 
class Solution { public:   int minInsAndDel(int A[], int B[], int N, int M) {       vector<int> lis;              unordered_set<int> s;       for(int i = 0; i < M ;i++){           s.insert(B[i]);       }                     for(int i = 0; i < N ;i++){           if(s.find(A[i])!=s.end()){               auto it = lower_bound(lis.begin(),lis.end(),A[i]);               if(it==lis.end()){                   lis.push_back(A[i]);               }else{                   *it = A[i];               }           }       }              return N+M-2*lis.size();   }};
// { Driver Code Starts.
int main() {   int t;   cin >> t;   while (t--) {       int N,M;       cin>>N>>M;              int A[N], B[M];       for(int i=0; i<N; i++)           cin>>A[i];       for(int i=0; i<M; i++)           cin>>B[i];
       Solution ob;       cout << ob.minInsAndDel(A,B,N,M) << endl;   }   return 0;}  
0
karthiksamineni1112 months ago
4 31 4 2 51 2 4
this input is giving 3 as output  plz explain.
0
ksandeep27072 months ago
C++ code:-
int minInsAndDel(int a[], int b[], int n, int m) 
    {
       map<int,int> mp;
       for(int i=0;i<m;i++)
          mp[b[i]]++;
       vector<int> v;
       
       for(int i=0;i<n;i++)
       {
           if(mp[a[i]])
           {
               auto it=lower_bound(v.begin(),v.end(),a[i]);
               if(it==v.end())
                 v.push_back(a[i]);
               else
                (*it)=a[i];
           }

       }
       
       int ans=n+m-2*v.size();
        return ans;
    }
0
araj2920183 months ago
class Solution { public:   //method of finding LCS using binary search   int LCS(vector<int> co){       vector<int>lcs;              for(int i=0;i<co.size();i++){           auto j=lower_bound(lcs.begin(),lcs.end(),co[i]);           if(j!=lcs.end()){              *j=co[i];            }           else{               lcs.push_back(co[i]);           }                  }       return lcs.size();   }   int minInsAndDel(int A[], int B[], int N, int M) {       vector<int>co;       unordered_set<int>s;       for(int i=0;i<M;i++){           s.insert(B[i]);       }       for(int i=0;i<N;i++){           if(s.find(A[i])!=s.end()){               co.push_back(A[i]);           }                  }       return N+M-(2*LCS(co));   }};
+5
neuron093 months ago
Trivial solution would be to use 2-D DP(simialar to https://leetcode.com/problems/edit-distance/) but since N could be upto 100K it will give TLE.
 First delete the nums in A which are not in B
Now we need to find LCS between A and B, and keep those elements in A and delete rest, and also add remaining numbers in B which don't occur in the LCS to make it equal to B
To find the LCS(longest common subsequence) with trivial 2-D DP will give TLE, but since B is already sorted, Longest increasing subsequence in A will be the LCS which can be found in O(N*LogN) time(similar to https://leetcode.com/problems/longest-increasing-subsequence/),
 Time: O(NlogN), Space: O(N)
class Solution {
  public:
    const int INF = 1e9 + 5;
    int lis(vector<int> a) {
        int n = a.size();
        vector<int> len;
        for(int i = 0; i < n; i++) {
            auto lb = lower_bound(len.begin(), len.end(), a[i]);
            if(lb != len.end()) {
                *lb = min(*lb, a[i]);
            }
            else {
                len.push_back(a[i]);
            }
        }
        return len.size();
    }
    int minInsAndDel(int a[], int b[], int n, int m) {
        unordered_set<int> b_set;
        for(int i = 0; i < m; i++) 
            b_set.insert(b[i]);
        vector<int> a_updated;
        int steps = 0;
        for(int i = 0; i < n; i++) {
            if(b_set.find(a[i]) != b_set.end()) {
                a_updated.push_back(a[i]);
            }
            else {
                steps++;
            }
        }
        int lis_size = lis(a_updated);
        return steps + (a_updated.size() - lis_size) + (m-lis_size);
    }
};
0
shashikantsolanki0423 months ago
Hint : First try to solve longest increasing subsequence problem.
 
class Solution {
  public:
    int solve(vector<int>vec){
        vector<int>res;
        for(int i=0; i<vec.size(); i++){
            auto it = lower_bound(res.begin(),res.end(),vec[i]);
            if(it == res.end()){
                res.push_back(vec[i]);
            }
            else{
                *it = vec[i];
            }
        }
        return res.size();
    }
    int minInsAndDel(int A[], int B[], int N, int M) {
        // code here
        unordered_map<int,int>mp;
        for(int i=0; i<M; i++){
            mp[B[i]]++;
        }
        vector<int>vec;
        for(int i=0; i<N; i++){
            if(mp.find(A[i]) != mp.end()){
                vec.push_back(A[i]);
            }
        }
        return (N+M) - 2*solve(vec);
    }
};
+2
shadyboy6 months ago
class Solution {
  public:
    int minInsAndDel(int A[], int B[], int N, int M) {
        vector<int> lis;// store longest increasing subsequence in nlogn time
        
        unordered_set<int> s;
        for(int i = 0; i < M ;i++){
            s.insert(B[i]);
        }
        
        
        for(int i = 0; i < N ;i++){
            if(s.find(A[i])!=s.end()){
                auto it = lower_bound(lis.begin(),lis.end(),A[i]);
                if(it==lis.end()){
                    lis.push_back(A[i]);
                }else{
                    *it = A[i];
                }
            }
        }
        
        return N+M-2*lis.size();
    }
};
0
divyanshchaudhri6 months ago
Can someone plz explain the question 
According to my understanding i wrote a code but one test case is not passing don't know why
test case is-
7 7 
1 9 7 4 9 8 9 
1 2 4 7 8 9 10
and the code is-
class Solution:   def minInsAndDel(self, A, B, N, M):       # code here       if(N>M):           x=N-M           c=0           for i in range(M):                             if A[i]!=B[i]:                   if B[i] in A:                       ind=A.index(B[i])                       temp=A[i]                       A[i]=A[ind]                       A[ind]=temp                       c+=2                   else:                               A[i]=B[i]                       c+=2               return x+c       else:           x=M-N           c=0           for i in range(N):                              if A[i]!=B[i]:                   if B[i] in A:                       ind=A.index(B[i])                       temp=A[i]                       A[i]=A[ind]                       A[ind]=temp                       c+=2                   else:                       A[i]=B[i]                       c+=2           return x+c           
 
0
shivanshushukla10246 months ago
why i am getting error in this approach While submitting:
 
class Solution:   def minInsAndDel(self, A, B, N, M):       # code here        count = 0       if(N == 0 and M == 0):           return count       for i in range(M):           if(A[i] != B[i]):               A.pop(i)               count += 1               A.insert(i, B[i])               count += 1       count += N-M       return count
0
itsanshika6 months ago
Find length of LIS of elements of A which are present in B
We need to delete all elements of A which are not in LIS and need to insert all elements of B which are not in LIS
Hence ans = N + M - 2*LIS_length
Thus we only need length of longest increasing subsequence of elements of A which are present in B
int LIS(vector<int> A, int N){
        if(A.empty()) return 0;
        vector<int> tail(N, 0);
        int len = 1; tail[0] = A[0];
        for (int i = 1; i < N; i++) {
            if (A[i] < tail[0]) tail[0] = A[i];
            else if (A[i] > tail[len - 1]) tail[len++] = A[i];
            else {
                int pos = lower_bound(tail.begin(), tail.begin()+len, A[i])-tail.begin();
                tail[pos] = A[i];
            }
        }
        return len;
    }
    
    
    int minInsAndDel(int A[], int B[], int N, int M) {
        vector<int> arr;
        map<int,int> m;
        for(int i = 0; i < M; i++) m[B[i]]++;
        for(int i = 0; i < N; i++){
            if(m.find(A[i]) != m.end()) arr.push_back(A[i]);
        }
        int len = LIS(arr, arr.size());
        return N+M-2*len;
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.