Merge Two Sorted List

Merge Two Sorted List

Given two sorted integer arrays A and B, merge B into A as one sorted array.

Note: You have to modify the array A to contain the merge of A and B. Do not output anything in your code.

TIP: C users, please malloc the result into a new array and return the result.

If the number of elements initialized in A and B is m and n respectively, the resulting size of array A after your code is executed should be m + n

Example :

Input : A : [1 5 8] B : [6 9]

Modified A : [1 5 6 8 9]

In this question, we can iterate both lists at the same time and then add the smaller one to another vector result then for the remaining array which was left we add it to the result

void Solution::merge(vector<int> &A, vector<int> &B) {
    int a=0,b=0;
    vector<int> res;
    while(a<A.size() && b<B.size())
    {
        if(A[a]>B[b])
        {
            res.push_back(B[b++]);
        }
        else if(A[a]==B[b])
        {
            res.push_back(B[b++]);
            res.push_back(A[a++]);
        }
        else if(A[a]<B[b])
        {
            res.push_back(A[a++]);
        }
    }
    while(a<A.size())
    {
        res.push_back(A[a++]);
    }
    while(b<B.size())
    {
        res.push_back(B[b++]);
    }
    A.clear();
    A=res;
}

In the above code, we made a new array so we used extra space of O(M+N), and the time complexity is O(M+N). to solve this problem now we are given 2 linked lists and we have to merge them.

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode *t1=new ListNode;
        ListNode *ans=t1;        
        while(l1 && l2)
        {
            if(l1->val<=l2->val)
            {
                ListNode *temp=new ListNode(l1->val);
                t1->next=temp;
                l1=l1->next;
            }
            else
            {
                ListNode *temp=new ListNode(l2->val);
                t1->next=temp;
                l2=l2->next;
            }
            t1=t1->next;
            //l1=l1->next;
        }
        while(l1)
        {
            ListNode *temp=new ListNode(l1->val);
            t1->next=temp;
            t1=t1->next;
            l1=l1->next;
        }
        while(l2)
        {
            ListNode *temp=new ListNode(l2->val);
            t1->next=temp;
            t1=t1->next;
            l2=l2->next;
        }
        return ans->next;
    }
};