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.
Time : O(nlogn)
Space : O(min(n,m))
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { //lis solution public: intminInsAndDel(int A[], int B[], int N, int M){ unordered_set<int> us(B, B + M); vector<int> lis; for(int i = 0; i < N; i++) { if(!us.count(A[i])) continue; if(lis.empty() or lis.back() < A[i]) lis.push_back(A[i]); else { auto lb = lower_bound(begin(lis),end(lis),A[i]); *lb = A[i]; } } return N + M - 2 * lis.size(); } };
Time : O(nm)
Space : O(nm)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { // lcs solution public: intminInsAndDel(int A[], int B[], int N, int M){ vector<vector<int>> dp(N + 1, vector<int>(M + 1));