L26. Sort a Linked List | Merge Sort and Brute Force

Поделиться
HTML-код
  • Опубликовано: 27 янв 2025

Комментарии • 127

  • @mohammadusman9701
    @mohammadusman9701 6 месяцев назад +119

    came here to learn on how to sort a linkedlist
    then went back to learn merge sort - hated striver
    then went back to learn how to merge two sorted linkedlist- hated striver
    then went back to learn the tortoise hare method(middle) - hated striver
    then came back and understood everything easily - loving striver

    • @avengergirl_0464
      @avengergirl_0464 6 месяцев назад

      😮😮😮

    • @ThePROestRedn99
      @ThePROestRedn99 6 месяцев назад +16

      If u will jump into middle of the course...This will obviously happen

    • @brokegod5871
      @brokegod5871 6 месяцев назад +11

      Why are you learning linked list when you don't even know a basic sorting algorithm?

    • @Ayush37262
      @Ayush37262 5 месяцев назад +12

      Aur phir yahi log khete hai ki bhaijaan kiya toh sab kuch, select phir bhi nahi hua...

    • @JyothiBomminayani
      @JyothiBomminayani 5 месяцев назад +1

      where is the video of merge two sorted linkedlist

  • @abbie1103
    @abbie1103 8 месяцев назад +74

    You use recursion very well in real life...
    In L26 - I have explained this in previous lecture(L24) go watch that;
    In L24 - I have explained this in previous lecture go watch that;
    and so on... till you reach the base video;
    No offense, just a catch.
    Your videos are really good, helped me alot.
    Thanks👍

    • @xrishabh
      @xrishabh 7 месяцев назад +6

      Recursive Nature

    • @harshchauhan5514
      @harshchauhan5514 20 дней назад +1

      Obviously Why will he reexplain same thing again. its not optimal🙃

  • @rushidesai2836
    @rushidesai2836 9 месяцев назад +27

    One of the best questions on LinkedList for sure!

  • @IamNikhil2121
    @IamNikhil2121 Год назад +24

    Time stamps
    intro :- 0:00
    brute force :- 0:45
    Better (merge sort) :- 6:20
    complexity analysis :- 19:25

  • @xperthighlight
    @xperthighlight 4 месяца назад +10

    bro after landing in this video by following your a2z sheet , I have been redirecting like a linked list to its previous again and again until I met a base case 🤣🤣🤣🤣

  • @HARSHBAID-m5f
    @HARSHBAID-m5f Год назад +12

    Thanks for sharing brother , i am on recursion topic learning consistently , feel good that even today you upload videos consistently in this inspiring helping 1000's of people , Thanks for that and More Power to you..

  • @abudanish196
    @abudanish196 Год назад +9

    Understood! Man you are a Legend!!!

  • @jatinpandey6453
    @jatinpandey6453 Год назад +16

    For the people who are finding to do this problem in O(1) space complexity (follow up from leetcode, coding ninja, etc):
    You shouldn't ! cos theres no one who does in O(1) sc either they use merge sort or create a new Linked List (with same length of input).
    Solution: Only way you you can do this in constant space is by using merge sort iteratively, which is again very complex solution and is of 100 lines of codes. And i dont think interviewer will give us this much time.

    • @jatinpandey6453
      @jatinpandey6453 Год назад +1

      the whole 100 lines of code is just passing on edge cases after edge cases i dont think you should do these but still posting the solution

    • @jatinpandey6453
      @jatinpandey6453 Год назад +4

      i dont know this man has achived this :
      public class Solution {
      private class MergeHelper {
      public ListNode newHead;
      public ListNode newTail;
      }
      public ListNode sortList(ListNode head) {
      if ( head == null || head.next == null) {
      return head;
      }

      ListNode dummyHeadOne = new ListNode(0);
      ListNode dummyHeadTwo = new ListNode(0);
      ListNode dummySortedHead = new ListNode(0);
      ListNode dummySortedLast = dummySortedHead;
      ListNode unvisitedNode = head;
      MergeHelper mergeRst = new MergeHelper();

      int listLength = 0;
      int level = 0;
      while ( unvisitedNode != null && unvisitedNode.next != null ) {
      unvisitedNode = addNode ( dummyHeadOne, unvisitedNode, 1

    • @RAJADHANISH23BCE984
      @RAJADHANISH23BCE984 3 месяца назад

      can do insertion sort right?

    • @yashwanthyerra2820
      @yashwanthyerra2820 2 месяца назад

      @@RAJADHANISH23BCE984 Insertion sort will increase time complexity to O(n^2)

  • @unknown76436
    @unknown76436 11 месяцев назад +3

    Brute force solutions
    ListNode* sortList(ListNode* head) {
    vector arr;
    ListNode* temp = head;

    // Extract values from the linked list and store them in the vector
    while(temp != nullptr){
    arr.push_back(temp->val);
    temp = temp->next;
    }

    // Sort the vector
    sort(arr.begin(), arr.end());

    // Update the linked list with sorted values
    temp = head;
    for(int i = 0; temp != nullptr; i++){
    temp->val = arr[i];
    temp = temp->next;
    }
    return head;
    }

  • @souvik33and37
    @souvik33and37 6 месяцев назад +1

    this person is a real legend

  • @vb6163
    @vb6163 10 месяцев назад +2

    ur vid are so good keep it up bro love u see ya bye

  • @jeet-smokey
    @jeet-smokey 7 месяцев назад +1

    Outstanding Explanation....!!!

  • @atharvalole4912
    @atharvalole4912 2 месяца назад

    came here watched first three minutes.....regretted after seeing a simple soln and went back!

  • @snehashisratna9074
    @snehashisratna9074 Год назад +1

    luv the way you teach ;

  • @Kanterneit
    @Kanterneit Месяц назад

    I think at 21:39 the Space Complexity won't be O(1), the reason being that the recursion stack adds up to Space Complexity of O(log N). But anyways there's no explicitly auxiliary space is being used, so the reasoning is always O(1).

    • @sleepypixie8828
      @sleepypixie8828 Месяц назад

      isn't recursion stack O(N)? If no can you pls explain why?

  • @dipraj.here07
    @dipraj.here07 Месяц назад

    whata beautiful question it is❤

  • @prathamIsOp
    @prathamIsOp Год назад +3

    C++ CODE | Leetcode Solution to Sort List:
    ⚡⚡
    ListNode* findMiddleNode(ListNode* head) {
    if (head == NULL || head->next == NULL) {
    return head;
    }
    ListNode* slow = head;
    ListNode* fast = head->next; // head->next because we want slow to point to the first element/middle in the even length case
    while (fast != NULL && fast->next != NULL) {
    slow = slow->next;
    fast = fast->next->next;
    }
    return slow;
    }
    // merge linked list function
    ListNode* merge(ListNode* list1Head, ListNode* list2Head) {
    ListNode* dummyNode = new ListNode(-1); // can be any value
    ListNode* temp = dummyNode;
    while (list1Head != NULL && list2Head != NULL) {
    if (list1Head->val val) {
    temp->next = list1Head;
    temp = list1Head;
    list1Head = list1Head->next;
    } else {
    temp->next = list2Head;
    temp = list2Head;
    list2Head = list2Head->next;
    }
    }
    // if list1 still has elements left
    while (list1Head != NULL) {
    temp->next = list1Head;
    temp = list1Head;
    list1Head = list1Head->next;
    }
    // if list2 still has elements left
    while (list2Head != NULL) {
    temp->next = list2Head;
    temp = list2Head;
    list2Head = list2Head->next;
    }
    return dummyNode->next;
    }
    // MergeSort recursive
    ListNode* sortList(ListNode* head) {
    if (head == NULL || head->next == NULL) {
    return head;
    }
    ListNode* mid = findMiddleNode(head);
    ListNode* leftHead = head;
    ListNode* rightHead = mid->next;
    mid->next = NULL; // Disconnect the left and right halves
    leftHead = sortList(leftHead);
    rightHead = sortList(rightHead);
    return merge(leftHead, rightHead);
    }

  • @montyk.151
    @montyk.151 8 месяцев назад +2

    The question given in the sheet asks to find it in O(1) space complexity

  • @NazeerBashaShaik
    @NazeerBashaShaik 8 месяцев назад +2

    Understood, thank you.

  • @riyashah1161
    @riyashah1161 5 дней назад

    love the vids tho, keep it up!

  • @MohdSaquibMansoori
    @MohdSaquibMansoori 3 месяца назад

    If the algo is using recursion then it will take s.c to be O(log n). Then it will still no an optimized version.

  • @sumitkumartah2106
    @sumitkumartah2106 10 месяцев назад +3

    Hey striver, we can do it by using prority queue also.

    • @Satyam-je4tb
      @Satyam-je4tb 4 месяца назад

      class Solution {
      public:
      ListNode* sortList(ListNode* head) {
      priority_queue pq;
      ListNode* temp = head;
      while(temp != NULL)
      {
      pq.push(temp->val);
      temp = temp->next;
      }
      temp = head;
      while(temp != NULL && !pq.empty())
      {
      int top = pq.top();
      pq.pop();
      temp->val = top;
      temp = temp->next;
      }
      return head;
      }
      };

    • @shifteditz06
      @shifteditz06 3 месяца назад +1

      but space complexity will be O(n), and in this video solution it is O(1)

  • @Gg69696
    @Gg69696 5 месяцев назад +1

    thnx striver

  • @mainakdasgupta7130
    @mainakdasgupta7130 10 дней назад

    thank you man

  • @YourCodeVerse
    @YourCodeVerse 11 месяцев назад

    Understood✅🔥🔥

  • @varunshridhar1310
    @varunshridhar1310 10 месяцев назад +1

    Do we need to consider recursion stack space?

  • @pratyushtripathi1728
    @pratyushtripathi1728 Год назад +1

    Understood 😊

  • @aryasharma69
    @aryasharma69 4 месяца назад

    S.C. will be Log(n) for using extra recursive space

  • @siddiqabr7110
    @siddiqabr7110 3 месяца назад +1

    21:37 we're creating a new node and copying all the elements isn't that O(n) space?

    • @yashwanthyerra2820
      @yashwanthyerra2820 2 месяца назад +1

      No since we are merging it inplace. as we are just chaging pointers using single dummy node

    • @siddiqabr7110
      @siddiqabr7110 2 месяца назад +1

      @yashwanthyerra2820 yeah yeah i realised it on that day when i commented this

  • @ArpitaChoudhury_00
    @ArpitaChoudhury_00 7 месяцев назад

    Thank You🙏

  • @sadiqnaqvi991
    @sadiqnaqvi991 10 месяцев назад +5

    But sir, with merge sort, we are again using auxiliary space in the stack by using recursion. So by brute force or Merge sort, space is still exhausting, right?

    • @dakshsingh5891
      @dakshsingh5891 8 месяцев назад

      stack space doesn't count as auxiliary space.

    • @Ayush37262
      @Ayush37262 5 месяцев назад +9

      ​@@dakshsingh5891 If you don't know something, at least don't give others false information.
      Recursion stack space is counted as auxiliary space.

    • @dakshsingh5891
      @dakshsingh5891 5 месяцев назад +2

      @@Ayush37262 okk bro i didn't know!!

    • @HR-pz7ts
      @HR-pz7ts 3 месяца назад

      Jyada dimag lga rha h bkl

  • @prasanjit.bhanja
    @prasanjit.bhanja 6 месяцев назад

    Legend 😊

  • @-FlyingZoro106
    @-FlyingZoro106 10 месяцев назад

    Thanks a lot

  • @abhishek-u7c
    @abhishek-u7c 13 дней назад

    can we do it by sorting(head->next) and insert(head) at correct position using recursion
    same way how we sorted a stack using recursion

  • @om3478
    @om3478 27 дней назад

    understood!!!

  • @riyashah1161
    @riyashah1161 5 дней назад

    please keep your video on the left, we're all used to it being that way ;-;

  • @Learnprogramming-q7f
    @Learnprogramming-q7f 11 месяцев назад

    Thank you Bhaiya

  • @Oldmonk3321
    @Oldmonk3321 8 месяцев назад +1

    🔥

  • @DeadPoolx1712
    @DeadPoolx1712 4 месяца назад

    UNDERSTOOD;

  • @soumi6720
    @soumi6720 7 месяцев назад

    the legend

  • @subee128
    @subee128 Год назад

    Thanks

  • @ancitamendonca7329
    @ancitamendonca7329 3 месяца назад +1

    how do the sorted lists get merged?

  • @charanhr6433
    @charanhr6433 6 месяцев назад

    🎉🎉

  • @adityasahni5262
    @adityasahni5262 9 месяцев назад

    Doesn't the optimal approach takes O(logn) space as it creates logn call stacks.

  • @oyeshxrme
    @oyeshxrme 6 месяцев назад

    bhaiya has done some recursion here

  • @AnshulSharma-gq2vn
    @AnshulSharma-gq2vn 10 месяцев назад

    ❤❤

  • @harigs72
    @harigs72 4 месяца назад

    🎉❤

  • @abhinanda7049
    @abhinanda7049 9 месяцев назад

    understood

  • @_PRANAYMATE
    @_PRANAYMATE 11 месяцев назад +2

    Hey striver do we not need to count the stack space storing n function calls while calculating the space complexity

  • @AshwinRB-yi3kf
    @AshwinRB-yi3kf 4 месяца назад

    I'm curious, why do we stop at the first middle and not the second??

    • @AshwinRB-yi3kf
      @AshwinRB-yi3kf 4 месяца назад

      Ok i figured it out, for those who didnt
      In the case your divided list is say 4 -> 2, the middle value according to the tortoise and hare algorithm will always be 2.
      This means if we divide the linked list into 2 halves left and right, left will always be equal to the original list, which results in stack overflow

  • @knowthrvdo
    @knowthrvdo 11 месяцев назад +1

    NICE LECTURE AND PLZ UPLOAD REMAINING LECTURES OF A TO Z SDA SHEET PLZ THEY ARE VERY HELPFULL FOR US

  • @arujain1690
    @arujain1690 8 месяцев назад

    How space complexity is constant O(1) ? We are creating a new LL (dummy node) and returning it so it should be o(N) right?

    • @adityabhanugarg3516
      @adityabhanugarg3516 8 месяцев назад

      we are just changing pointers of already given two linked lists

    • @vishalgupta7522
      @vishalgupta7522 7 месяцев назад

      just delete the dummy node then no extra space is required

  • @rishabh7215
    @rishabh7215 7 месяцев назад

    can anyone explain why do we initialize Node* fast = head->next instead of just head in the tortoise-hare method?

    • @madhu_mohanreddy
      @madhu_mohanreddy 6 месяцев назад

      18:50

    • @avengergirl_0464
      @avengergirl_0464 6 месяцев назад +1

      Bcoz as we want 1st mid in this case....if we put fast on head->next ...it will end one step early and so slow will be on 1st mid instead of 2nd mid

    • @ninaad765
      @ninaad765 5 месяцев назад +1

      exactly, i was confused too
      @avengergirl_0464 why 1st, 2nd mid? that's only if there's even number of nodes...?

    • @avengergirl_0464
      @avengergirl_0464 5 месяцев назад +1

      @@ninaad765 dry run urself u will understand

  • @mikeag1371
    @mikeag1371 10 месяцев назад

    merge sort also taking O(n) space i guess??

  • @nayankhuman1043
    @nayankhuman1043 4 месяца назад

    understood :)

    • @anotherlostspirit
      @anotherlostspirit 4 месяца назад

      hi, I on't understand the part where we must set fast = head.getNext() to place it 1 steps ahead the slow node, and why does slow need to stops at m1, am I missing something from the video?. I've watch the "how to find middle of Linked List" too and still doesnt know why we need that adjustment. Also I'm replying your comment cuz this is the latest comment, sorry if this borders you. Have a great day sir

    • @shobhitmishra739
      @shobhitmishra739 2 месяца назад

      ​@@anotherlostspirit
      In the case your divided list is say 4 -> 2, the middle value according to the tortoise and hare algorithm will always be 2.
      This means if we divide the linked list into 2 halves left and right, left will always be equal to the original list, which results in stack overflow

  • @vinayaksai_akula
    @vinayaksai_akula 3 месяца назад

    def sortLL(head):
    a=[]
    temp=head
    if head is None or head.next is None:
    return head
    while temp!=None:
    a.append(temp.data)
    temp=temp.next
    a.sort()
    temp=head
    for i in a:
    temp.data=i
    temp=temp.next
    return head

  • @easylearn8924
    @easylearn8924 Год назад

    can anybody tell why we do fast=head->next?? if we dont do that it gives runtime error??

    • @chitranshsrivastava5880
      @chitranshsrivastava5880 11 месяцев назад

      Do a dry run you'll easily know why it is giving runtime error.

    • @shreyxnsh.14
      @shreyxnsh.14 11 месяцев назад +1

      you can also do this:
      ListNode* slow = head;
      ListNode* fast = head;
      while(fast->next!=NULL && fast->next->next!=NULL){
      fast = fast->next->next;
      slow = slow->next;
      }
      return slow;

    • @ninaad765
      @ninaad765 5 месяцев назад

      @@shreyxnsh.14 does that work? instead of fast=head->next? (i was thinking it should be = head)

  • @KumarjiIndia
    @KumarjiIndia Год назад

    Trees please 😉

  • @lifehustlers164
    @lifehustlers164 Год назад +4

    first comment

  • @YashGaneriwal-je6rh
    @YashGaneriwal-je6rh 5 месяцев назад

    done and dusted

  • @IBMX65
    @IBMX65 5 месяцев назад

    7:00

  • @mohitsingh7793
    @mohitsingh7793 7 месяцев назад

    class Solution {
    public:
    ListNode* findMiddle(ListNode *head)
    {
    ListNode *slow,*fast,*temp;
    temp=slow=fast=head;
    while(fast && fast->next)
    {
    temp=slow;
    slow=slow->next;
    fast=fast->next->next;
    }
    if(!fast)
    return temp;
    return slow;
    }
    ListNode *merge(ListNode *listA,ListNode *listB)
    {
    ListNode *head=new ListNode();
    ListNode *root=head;
    while(listA && listB)
    {
    if(listA->valval)
    {
    head->next=listA;
    listA=listA->next;
    }
    else
    {
    head->next=listB;
    listB=listB->next;
    }
    head=head->next;
    }
    while(listA)
    {
    head->next=listA;
    listA=listA->next;
    head=head->next;
    }
    while(listB)
    {
    head->next=listB;
    listB=listB->next;
    head=head->next;
    }
    return root->next;
    }
    ListNode *mergeSort(ListNode * head)
    {
    if(!head || !head->next)
    return head;
    ListNode *middle=findMiddle(head);
    ListNode *leftHead=head;
    ListNode *rightHead=middle->next;
    middle->next=NULL;
    leftHead=mergeSort(leftHead);
    rightHead=mergeSort(rightHead);
    return merge(leftHead,rightHead);
    }
    ListNode* sortList(ListNode* head) {
    return mergeSort(head);
    }
    };

  • @rs-oz9jk
    @rs-oz9jk Год назад

    where is the code man?

  • @VarunSharma-xd8xd
    @VarunSharma-xd8xd 9 месяцев назад

    public class Solution {
    public static Node sortList(Node head) {
    if(head==null || head.next==null){
    return head;
    }

    Node ih=head;
    Node dh=head.next;
    Node ic=ih;
    Node dc=dh;

    while(dc!=null && dc.next!=null){
    ic.next=dc.next;
    dc.next=dc.next.next;
    ic=ic.next;
    dc=dc.next;
    }

    // till now we have seperated both the lists
    dh=reverse(dh);

    // now need to merge these 2
    return merge(ih,dh);
    }

    public static Node reverse(Node head){
    Node curr=head;
    Node prev=null;
    while(curr!=null){
    Node next=curr.next;
    curr.next=prev;
    prev=curr;
    curr=next;
    }
    return prev;
    }

    public static Node merge(Node left,Node right){
    Node dummy=new Node(0);
    Node curr=dummy;
    while(left!=null && right!=null){
    if(left.data

    • @yashwanthyerra2820
      @yashwanthyerra2820 2 месяца назад

      bro i dont know why you are using reverse here.probably that might be the bug

    • @yashwanthyerra2820
      @yashwanthyerra2820 2 месяца назад

      replace reverse with recursive mergeSort

  • @sri-z5d
    @sri-z5d 6 дней назад

    22-01-25

  • @PawanKumar-hq6dy
    @PawanKumar-hq6dy 2 месяца назад

    will this be taking NLOGN time compelexity and O(N) space
    public ListNode sortList(ListNode head) {
    if(head == null || head.next == null) return head;
    ListNode dummy = new ListNode();
    ListNode dummyHead = dummy;
    ListNode temp =head;
    PriorityQueue pq = new PriorityQueue((a,b)-> a.val-b.val);
    while(temp!=null){
    pq.add(temp);
    temp = temp.next;
    }

    while(!pq.isEmpty()){
    // System.out.println(pq.peek().val);
    ListNode next = pq.poll();
    next.next = null;
    dummy.next = next;
    dummy = dummy.next;
    }
    return dummyHead.next;
    }

  • @Anonymous____________A721
    @Anonymous____________A721 6 месяцев назад

    Its not short!!!!!!!

  • @cenacr007
    @cenacr007 8 месяцев назад

    us

  • @sanjanaaa17
    @sanjanaaa17 4 месяца назад

    Personally didn't like this video. If i am spending 22 mins on your video you should explain everything and not redirect to xyz videos here and there. At least summarize the code even if it is already covered in some other video :/

  • @ShubhamSharma-oq4hr
    @ShubhamSharma-oq4hr 10 месяцев назад +19

    I really hate when you say go back and watch it, its very annoying

    • @gdppwow
      @gdppwow 9 месяцев назад +18

      Just watch it and comeback.

    • @Lalala_1701
      @Lalala_1701 7 месяцев назад

      Go back bro

    • @abhishekg2766
      @abhishekg2766 6 месяцев назад +14

      Bruhhhh getting this content is really hard and he is giving it for free so stop whining and go watch it 😮‍💨

    • @Adarshrai6339
      @Adarshrai6339 5 месяцев назад +13

      Bro you want him to explain same topic again and again🤡

    • @irfanmohammad2132
      @irfanmohammad2132 2 месяца назад

      🤡

  • @CompetitiveProgramming-b5r
    @CompetitiveProgramming-b5r Год назад

    Hey Striver you look chuby♥

  • @SibiRanganathL
    @SibiRanganathL 9 месяцев назад

    Understood

  • @siddiqabr7110
    @siddiqabr7110 4 месяца назад +1

    0:45 I'm not bragging or anything but not in a million years i think of a brute force like these how can you come up with brute force methods 😅😅

  • @Czjajava
    @Czjajava 4 месяца назад

    Bura mat manna i never understood not even a single question what u have taught so far in ur videos....

  • @dewanandkumar8589
    @dewanandkumar8589 8 месяцев назад

    Understood

  • @ramakrishnakcr4417
    @ramakrishnakcr4417 9 месяцев назад

    understood

  • @arnabkundu1648
    @arnabkundu1648 7 месяцев назад

    Understood

  • @hardikpatel352
    @hardikpatel352 8 месяцев назад

    understood

  • @abhinavabhi3568
    @abhinavabhi3568 3 месяца назад

    Understood

  • @abhishekprasad010
    @abhishekprasad010 8 месяцев назад

    understood

  • @riaa55
    @riaa55 Месяц назад +1

    Understood

  • @himasreedadam7670
    @himasreedadam7670 Месяц назад

    understood