Lecture 49: Merge 2 Sorted Linked Lists || Sort 0s, 1s and 2s in Linked List

Hello ji, how are you all ? this is Love Babbar And welcome to the Channel Code help , so this is our lecture no-49 here we will do very good questions , 1 will be easy and 1 will be medium Easy 1 is not that much easy ,you will enjoy it, Sort 0s , 1s ,2s in linked list So you will have a linked list in input ,lets 1st understand it You will have a linked list like this In output I need to sort it ,0->1->1->2->2->NULL , this is my head Simple not that much hard , I would be given a linked list in which elements will be in random order There will be 3 types of elements 0 ,1 ,2 in random order I have to give this type of linked list in output, are you getting it We have to solve it, what will be the approach ? We will discuss it from basics ,Lets give shout out to video sponsors so that our rhythm doesn't break This video is sponsored by Relevel ,it is India's 1st hiring platform Helps you to grab your dream job , there is no need of experience and degree You can grab your dream job by just cracking the test The best thing is that you didn't need to pay money Relevel is conducting tests in 9 categories , which are visible here Some new categories has been added ,operation associate test ,H R generalist test , associate product management test Which provides salaries around 25 LPA Jobs are offered from 200 big companies like Paytm , Razer pay , CRED , etc If you are unable to decide There is mock test section also , go and practice You will get the idea of questions asked by companies , Relevel has already provided 10 crore + worth jobs Here you can get up to 40 LPA packages These are the some examples of achievers If you are able to maintain yourself at monthly leaderboard Then you can win exciting prizes like Mac , iphone , apple watch ,etc Go to these platform , register , book the test After cracking the company mail me Got the placement now tell me where to give the party ,thank you Lets talk about the approach 1st thing I am understanding that , there is one 0, so I put it Then there are two 1s , put them here How many 2s? so I also put them here , 1st algorithm can be , if my linked list is of this type Do traversing and count the no.

Of times an element is present no. and here the count 0 -> 1 ,1s->2 ,2s->2 By traversing we got the count , 0 -> 1 ,1s->2 ,2s->2 If now I move like this , then put 0 here 1s ->2 ,Then we made it one , this also 2s->2 ,you filled both places with 2 So my resulting linked list is 0->1->1->2->2->NULL and this is the answer This is one way , here we count the no.

The times element is occurring , and replacing the data Lets code it , so that you can understand it, its easy int zeroCount =0 , int oneCount=0 ,int twoCount=0 Now traverse the linked list one time , Node* temp= head , while(temp != NULL) if(temp->data ==0) , zeroCount++ esle if( temp->data==1) , oneCount++ esle if (temp->data ==2) , twoCount++ temp=temp->next Then traverse the list and replace the data I again initialized temp ,while( temp != NULL) if(zeroCount !=0) , temp->data =0 Lets write again ,there will be two things temp->data =0 ,zeroCount– esle if( oneCount !=0) ,temp->data =1 ,oneCount– Same for 2 ,esle if ( twoCount !=0) , temp-.data= 2 ,twoCoiunt– temp= temp->next Then we will return head , question is solved T.C-> O(n)+ O(n) =2 O(n) = O(n0 Here we have used some variables , so S.C -> O(1) Lets run it , correct answer , submit it So we saw the first approach , correct answer So we have understood it , we are traversing , counting all no.s How much times 0 came? , same for 1 and 2 Then we will replace them , simple , this is 1st approach Approach -2 ,if you tell this approach , then interview will accept it but will ask you not to replace data So in approach -2 condition is not to replace the data data replacement is not allowed , from this statement we know that what we have to think If my linked list is of this type It is given data replacement is not allowed , then what I can replace only the links or pointers , now my approach should be to change the links I have to think something related to links , so that I can get my output data So know this , there are two things in linked list data and pointers So here we are talking about pointer , we have to change it , its simple Lets understand it, this is 1->0->2->1->2->NULL, and this is your head If I make 3 different linked lists , one for 0 , one for 2 ,and one for 2, And then merge them , can we do it ,lets see I will make 3 linked list , one for 0 ,one for 1 and one for2 We pointed current pointer here , this is 1 , it will be added here Then it shifted by one ,then 0 is added here , 2 is added here , and i came here , there is 1 , so it here then here , there is 2 , so it is added here , it reached NULL, here I will stop So this is your while loop condition, there are 3 linked list for 0 ,1 ,2, then merge them 0->1->1->2->2->NULL, solved This is the logic So in this way we are going to do it, there is a catch There is a catch of dummy node, here we are making a linked list In start there is a dummy node, in short when I say , there is a dummy node In same way there is a dummy node in 1 ,2 also In front of 0 I placed 0 , then here 2 1s , then two 2s, in front of these dummy nodes Why these dummy nodes needed , we will understand it now , when we have to merge these three lists If there is no dummy node then it will be very difficult , we can do it but we will have to many if conditions That's why I have used dummy node here , are you getting it?, Why part must be clear Did you got it? lets code it to understand Lets do it , 1st I need 3 dummy nodes , Node* zeroHead=new Node() here I entered some data , -1 Node* oneHead=new Node(-1) Node* twoHead=new Node(-1), so I created 3 dummy nodes I created a zeroTail=zeroHead In starting there are two pointers on dummy node, why we used it ? You will get it ,Assume here you got 1 , so I put it here, in short it is the tail Then I got this 1 , then I put it here , insert at tail , so I should know the tail that's why I created it In same way I said Node* onetail=oneHead Node* twotail =twoHead So I created 6 pointers , lets move to loop Node* curr=head ,while (curr !=NULL) ,int value=curr->data If ( value==0) ,then put it to 0s list populate(zerotail ,curr) else if (value == 1) , insertAtTail( oneTail ,curr) else if(value==2) , insertAtTail(twoTail ,curr) curr=curr->next ,because we have to end the loop 1st write the function here , void insertAtTail(Node* &tail ,Node* curr) I want to put it in tail ,tail->next = curr ,tail=curr So we have understood till now Here i have created separate list for 0s , 1s ,and 2s Merge these 3 sub lists In merging we will use dummy node , here we will use our minds Here are 3 lists and we have to merge them Here tail is pointing to zero , same for 1 and 2 Let me make it more clear , so that you can understand it better This is 0s head , and zeroTail is here , same for 1 and 2 And I have to merge them , how will we do it? Lets find it, I have to point 0s tail here basically, because there is no need of dummy node zeroTail->next=oneHead->next ,I will explain you Then oneTail->next= twoHead->next Here linked list is ending, so I want its next to point NULL ,twoTail->next=NULL There can be one mistake , there can be a case The 0s list contains 0 ,there is nothing is 1s list , in 2s list there are two nodes In this case when you will merge them , your above logic will not work here In 0s tail your are pointing this in this way , if this part is NULL then we have to put it here Make sure that here we have to use one if condition if(oneHead->next !=NULL) ,1st list is non empty In this the statement that we have written zeroTail->next=oneHead->next esle ,1s list is empty, then we have to take 2s list zeroTail->next=twoHead->next , in this way you used one if condition and your work will be done Lets code it to get the clarity, check if 1s list it not empty, 1s list is non empty ,in this case zeroTail->next=oneHead->next else ,1s list is empty zeroTail->next=twoHead->next So we have done it, now things are more clear Put 2s list after 1s list ioneTail->next=twoHead->next twoTail->next=NULL These are some statements which we have written here , after your 0s list some list will be added If 1s list is non empty ,then you put 2s list after it, then NULL Here you have completed the merge work ,now your list is looking like this Here is the dummy node , which name is zeroHead ,0 part is connected to it , then 1 part ,then 2 part, then NULL pointer This part is still indicated by a dummy node oneHead And this part by twoHead Now I don't need these , so delete them and I want that my list's head should point here ,and it is zeroHead->next position Basically I said Head =zeroHead->next ,logic is easy , but requires efforts So you set the head, now I have to delete these nodes delete dummy nodes , delete zeroHead delete oneHead delete twoHead Then I returned my answer Lets see the steps , 1st of all , I created some dummy nodes And created its head and tail pointers , and created separate linked list of 0 ,1 ,2 Then merge them , set the head Now delete the all dummy nodes and return my answer Run it , correct , lets submit it.

Correct answer What are the T.C and S.C ? T.C , lets see this loop is traversing one time , so here T.C ->O(n)+O(1) this is also single operation, these are some single operations , so they are taking constant time So answer is O(N) S.C ,here we have taken some variables and pointers , so my S.C is O(1) Previous solution also have the same complexity, traversed the whole list , then stored the counts Then replaced them, O(n) + O(n)=2 O(n) =O(n) and S.C ->O(1) But if interviewer ask data replacement is not allowed ,then you will change the links and we have saw it Now We will make 3 separate linked list for 0 ,1 ,2and then write the logic to merge them And will delete the dummy nodes , in this way we solved it Lets move to our 2nd question , Merge to sorted linked list Here most optimized solution will be provided, don't worry , here you have to use your mind a little bit more Interviewer will be impressed Lets see how we will solve it, 1st lets understand it I have two linked list 1st is 1->4->5->NULL, this is head1 2->3->5->NULL ,this is head2 , in output you will give sorted linked list by merging them 1->2->3->4->5->5->NULL, this is your head this is your output , you have to merge two sorted linked list , so that resultant linked list will be also sorted I will give you two linked list , by merging them give me one more sorted linked list Lets try to solve it, lets see how we can solve it Approach, lets see case by case Lets 1st read its constraints , is there anything extra t is no .

Of test cases , l is length , at least one , no list will be empty Assume we are trying to write generic code , if someone said there can be empty list also if(head1==NULL) ,it means 1st list is empty If 1st list is empty ,then did we need to merge something?, I will return head2 as answer ,vice versa is also possible ,then we will return head 1 These two case would have become clear to you , what more we can do? Lets see , if I have these two lists 1->3->5->NULL and 2->4->5->NULL Then in this case , this is my h1 and this is h2`, I will find the element that I can put in middle of my list If I get such element which I can put in between 1 and 2 ,then my work is done If not , then I will increment them, this will go here and this here Can I put here , are you getting it ? that's it 1->3->5->NULL and 2->4->5->NULL h1 is here and h2 here ,I will always take an element from other list And check , this is my prev and this is the curr , can I put this in between them, if yes then put it and it moved here , 1 step is completed Now point it here , can 4 come in between them ?no11 So lets write the condition, can it come in the middle I am representing with temp , prev->data <=temp->data <= curr->data If this is coming true , then put it in between of them And update the pointers , 2nd case false , if it is not coming then update your curr pointer So you placed curr here , and your prev is here Can I put it between 3 and 5, yes , so put it there Then 5, then we checked condition , yes , so put it there This list has become empty , so my answer is h1 If I see my answer carefully , 1->2->3->4->5->5->NULL that's it, you just checked the condition ,if true then put it if not then move the pointers forward bhaiya how to find the approach , simple , take a node from here And check whether we can put it or not then check next one You taken a node , and checked , can You put it here , if yes then put it if not then check the next one , lets implement it Lets code it , try to be with me From here we will begin it one is 1st and one is 2nd ,if(first== NULL) , return second same thing for 2nd also , if(second==NULL) , return first Lets make linked list once , then we will understand it These are the nodes In same way these are the node There are 1 ,3 , 5 and 2 ,4, 5 These are pointing like this There is first , and second So we have understood this part , we decided to pick the 1st element of 2nd list And check whether can it come in between them, if yes then put it If not , then we will move to next two, this was the plan In whichever list 1st element is smaller , we will take it as 1st list and 2nd one as second list But how? We have already named them If I create a function and on their values decide the 1st and 2nd lists Lets code it, if(first->data <=second->data)solve(first ,second) In same way else , solve(second , first) If I write this function here , void solve(Node<int>first , Node<int>second) In this case 1st data is small, so we sent first in 1st In this case 2nd data is small , so we sent second in 1st In short, we will always apply this logic , take the element of 2nd , check in 1st can we put it in between two elements or not If yes then put it , if not then move this window forward In this way we will do it , simple , so we will call the solve function I have to check this no.

In this window I named it curr1 , this next1, and this named it curr2 Lets initialize it, Node* curr1 =first ,Node* next1=curr->next Node* curr2=second , so we have taken 3 pointers Now what to do , we have to make sure that we should always check in this window So it should not happen that it reached here and you are checking it Make sure that it is not NULL In while we are saying , next1 != NULL And here we are traversing it also next1 !=NULL && curr2 != NULL , follow otherwise you will not able to understand it I will take this element , curr2 should not be NULL And I will check it in this window , make sure that next1 should not be NULL if you have put next1 !=NULL , then there is no need I have taught you the condition , we have to write this condition, If we see carefully , we are checking that this data lies in between them if( curr2 ->data >=curr1->data && curr2 ->data <=next1->data ) We have written this condition here If this happens , if this element lies in between them then put it Then what we need to do for it , I will remove this and point to 2, this is my 1st step curr1->next =curr1 2nd step , 2 is pointing to this , I want it to point this Then if I do this I will lose the track of this I want to save this , I will create a pointer ' next2' next2 =curr2->next Now I have track of this linked list Lets move to 3rd step , I will remove this and point it to this , curr2->next=next1 From these 3 steps 1 is pointed to 2 curr1=curr2 5 .

Curr2 = next2 We will go slowly , it will take time to understand it, from these 3 steps you added node here And here you are updating it, lets code it curr1->next =curr2 lets make it out side , Node*next2 = curr2 -> next next2 = curr2 ->next curr2 -> next=next1 Here we returned curr1 =curr2, curr2=next2 So in this way we have written it , lets move to our else part If part use to say that your data lies in this part , esle part says it doesn't lie So move pointer ahead For example , now my curr2 is pointing to 4, so we checked it, can it come between 2 ,3 no! So I have increment curr1 and next1 by 1 curr1=next1 ,next1=next1->next So we have to make sure next1 != NULL , lets check it else , if next1 has reached NULL, then this linked is finished In short , I will point curr1 here if next1 becomes NULL , then curr1 =->next=curr2 , return first There we don't need this else part Lets see if something it pending , just check the condition , if yes then ,make a node and update the pointer if not , then move them , but check the next1 !=NULL ,then return the answer return first I think we have done it, lets make it clear lets add some comments Is there anything pending Lets understand , 1st list is NULL ,so we returned second ,or if 2nd is NULL ,then return 1st one We will take element from 2nd list and compare it with elements of 1st list Make that list 1st whose elements are smaller , compared it , if 1st data is smaller then send 11st if not then send 2nd one I have to check in this range , this is curr1 and this is next1 You have to traverse both the list , so you check next1 and next2 != NULL If my this condition is true , then I will put the node , 2 lies between 1 and 3, then I will put it between them We have discussed it, I will move this pointer , and it 2 Then I will remove this pointer , and point it here Then I will increment them , these 5 things we have done here In else part , if this condition is not satisfied , there is a element that we can't put between them Then increment the pointers by 1 Write it in this way , both are same things Make sure your next1 is not NULL, if it is NULL, then point it to remaining part in 2nd list curr1 ->next= curr2 ,and you returned your answer your answer head will be 1st list head, so have written the function What is the complexity ? lets see we have made a simple function call , a loop is running here You are basically traversing the both linked list In worst case T.C-> O(n) , S.C->O(1) Lets run it , I think there is a little problem Lets check one test case , and run it , compilation failed Node* curr1= first , there is mistake in declaring Here you have made generic type structure What were you initialize to T , it will store that type of data In future when we will study it, then I will explain it to you Is there any more problem ? no !! Lets check it, return first Here we didn't returned as Node here we are returning the head Now run it , here it is giving correct Lets run it , this is also correct It is running properly , but still lest check it Whenever you use next , then check the case of NULL, otherwise it will segmentation fault At least we will get 1 element So I can say it Checking …

In else , here can be problem , assume There is one mistake , assume that we get a case like this , There is a list named f and it is pointing to NULL , in 2nd list there is one value and it is pointing to NULL Lets see what happens ,, these conditions will be not satisfied ,then we used these 4 pointers Here curr1 and here next1, in same way here curr2 and here next2 If you see carefully , if next1 is NULL then you will not enter the loop And you will return your answer But this is wrong In short , because of this condition , the case in which your linked list will have 1 element it will be not processed So we have to handle it , here one additional case will be used If only one element is present in 1st list we have to handle it , if there is 1st element in the list , then we will point to next list if (first->next ==NULL) , there is one element , then put the 2nd list first->next=second , return first I will run it , it should run Correct answer ,and submit it , correct answer Lets understand the logic once again We have to list 1->3->5->NULL This is the head1 , then there is 2->4->5->NULL, this is head2 And we have to merge them , take two elements and from here take the 1st element Can we put it here then put it , if not then take the next window Here we have write these , and also explained to you Our main logic lies here , if there is only one element , then point it to 2nd list If my 2nd list element satisfy the condition If satisfy this particular condition , then put it in between them Then update the pointers If not , Then update the window of1st list Go one step ahead in 1st list make sure that next is not NULL, if it is NULL , then your 1st list is finished Then simply point it here to 2nd list curr1->next=curr2 then we returned the answer , use your mind Tell me did you get it or not? we will use it again , this is a good question , can be asked in interviews We are doing good questions , which can be asked that's it for this video , tell me in the comment section Time? 5:52 am ,shoot is going on since 12:00 am , Bye Bye!!