Partially correct ans needs your help


#1
void Solution::merge(vector<int> &A, vector<int> &B) {
    int i = 0, j = 0 ;
    //Answer partially working (failing for large test cases apparently)
    //A.resize(A.size() + B.size()); 
    while(j < B.size()){
        if(A[i] < B[j]){
            i++;
           // continue;
        }
        else if(A[i] > B[j]) {
            auto posi = A.begin()+i;
            A.insert(posi, B[j]);
            i++;
            j++;
            //continue;
        }
        else {
            A.push_back(B[j]);
            j++;
        }
    }
    
}

Apparently, it is failing for large test cases. How do I rectify this? Please do let me know :smile:


#2

Instead of “A.push_back(B[j]);” in the else part, maintain the position and insert at the index. For example:
In the following test case:
2 -2147483648 3
3 -2147483648 -4 2147483647
where 2 and 3 are lengths of A and B respectively.
-2147483648 from B is not less than -2147483648 from A and hence the if and else if blocks won’t run, and in the else block it would be added as a push back at A which is after 3, which messes up things.


#3

What’s your solution? Do share it :smile:


#4
public class Solution {
public void merge(ArrayList<Integer> A, ArrayList<Integer> B) {
    int Acounter=0;
    for(int b:B){
        while(Acounter<A.size() && A.get(Acounter)<b) Acounter++;
        if(Acounter<A.size() && A.get(Acounter)>b) {
            A.add(Acounter,b);
            Acounter++;
        } else {
            A.add(Acounter, b);
            Acounter++;
        }
        
    }
}
}