Sort List - Merge Sort - Leetcode 148

  Рет қаралды 76,874

NeetCode

NeetCode

Күн бұрын

Пікірлер: 77
@NeetCode
@NeetCode 3 жыл бұрын
Linked List playlist: kzbin.info/www/bejne/fWHCemCQe5WGaZo
@anilalapati
@anilalapati Жыл бұрын
Hi, thank you for the video, I have one query , could you please help? Usually to find the middle of the linked list, we use slow and fast = head, why did we use fast= head.next here?
@lucasxy
@lucasxy 2 жыл бұрын
For audiences who do not understand how we connect dummy to tail node: Basically dummy and tail are two different POINTER nodes starting at the same spot of the Linked List we created. It is more accurate to understand them as POINTER instead of nodes. In the code we do dummy= tail= Node(), that means we created 2 different pointers starting at the same Linked List Node. Then going forward dummy node stays at the starting points, but tail pointer keeps moving forward, which is to add new nodes to the LinkedList we created. When we do return dummy.next, we are basically returning the entire Linked List we created, but trimming the beginning dummy node, because this is not part of the list1 or list2.
@carloslazarin
@carloslazarin Жыл бұрын
thank you a lot!
@JustCuter
@JustCuter 2 жыл бұрын
left = head mid = self.getMid(head) right = mid.next mid.next = None save one line of code and less confusing
@mohitsharma1981
@mohitsharma1981 Жыл бұрын
Thanks
@SURYA-w3k
@SURYA-w3k 3 ай бұрын
thanks
@linli7049
@linli7049 3 жыл бұрын
I think you are right. When I saw the nearly 100 lines of code for O(1) space complexity solution I was stunned.
@RohithMusic
@RohithMusic Жыл бұрын
This has O(log(n)) space complexity due to the recursion. Merge sort can be done iteratively log(n) times to get O(1) space complexity. Note that this is possible because we are using Linked list. If we were using an array we would need O(n) additional space anyway.
@tbad2009
@tbad2009 Жыл бұрын
space complexity in this code and any merge sort where we make new arrays (or linked lists) at each step is O(n)? why do you think it's O(log(n)) here?
@MichaelKao-dj9of
@MichaelKao-dj9of 11 ай бұрын
Not sure if something went wrong when I'm duplicating this code. But I met an error "RecursionError: maximum recursion depth exceeded". Fixed it by considering the boundary case: " if not head: return None if head.next == None: return head"
@butterfly34457
@butterfly34457 Жыл бұрын
Why is the initialization step in getMid() function slow, fast = head, head.next and not slow, fast = head, head like in the 876. Middle of the Linked List code?
@eslamwageh4461
@eslamwageh4461 7 ай бұрын
as here in this problem to get the middle node of linked list of 4 nodes we want to get the second node not the third like the 876 problem so he made the fast proceeds with one node to do this . trace a case of 4 node and you will get it
@jeromesimms
@jeromesimms 2 жыл бұрын
I'm interested to see the constant time solution that you mentioned 1:00 and I'm wondering if anyone knows where I could see it?
@KostyaZinoview
@KostyaZinoview Жыл бұрын
On leetcode at solutions section
@kalyanvejalla
@kalyanvejalla 2 ай бұрын
not constant time, constant space
@275phuongvy
@275phuongvy 3 жыл бұрын
can you make video solving this problem with 0(1) space complexity? because in the interview, they always expect you to come up with optimal solution. Anyway, Thank you for your great explanation
@nathanx.675
@nathanx.675 2 жыл бұрын
this is an O(1) space complexity solution
@yonahgraphics
@yonahgraphics 2 жыл бұрын
@@nathanx.675 Nope, recursive calls: O(logn)
@pravargupta6285
@pravargupta6285 Жыл бұрын
Well I did it in O(n) space complexity but time complexity became O(n^2), So maybe not worth it? Well it was insertion sort.
@ivaylokostadinov7543
@ivaylokostadinov7543 Жыл бұрын
@@pravargupta6285 but I think he is asking about O(1) space, not O(n)
@hoixthegreat8359
@hoixthegreat8359 Жыл бұрын
I don't think any interviewer will mind, so long as you note it is possible by making your code iterative. O(1) and O(logn) are so absurdly close it doesn't really matter. For a list of 4294967296 elements, the space complexity is only 32 times bigger versus the O(1) solution, whereas something with O(n) space would be 4294967296 times bigger.
@lethality3704
@lethality3704 2 жыл бұрын
this is the top down merge sort
@anmolgautam19
@anmolgautam19 Жыл бұрын
what's the space complexity of this problem.? is it still O(n) or O (log n)
@hoixthegreat8359
@hoixthegreat8359 Жыл бұрын
logn
@derekzhang9655
@derekzhang9655 2 жыл бұрын
I swear i hear league msgs in the background..... Great vid tho!
@lewisw29
@lewisw29 Жыл бұрын
I thought getting the mid node is O(n) so I gave up on merge sort when I thought of it lol
@KarthikNandanavanam
@KarthikNandanavanam 6 ай бұрын
I think getting mid is still 0(n)
@yonahgraphics
@yonahgraphics 2 жыл бұрын
Hey NeetCode, why does the fast pointer start at head.next? I thought they should start from the same point
@purrfectempire
@purrfectempire 2 жыл бұрын
I am confused about that one too. Let me know if you get the answer to that, please.
@GeetThaker
@GeetThaker 2 жыл бұрын
This is because, if there are even number of element in linked list, then there are two middle point, so using head.next for faster pointer, slow will stop at first middle point. for example 1->2->3->4, then slow will stop at 2. If we do not start our fast with head.next then slow will stop at 3. However it is not necessary here to do fast = head.next.
@dinesh6489
@dinesh6489 2 жыл бұрын
slow, fast=head,head while fast.next and fast.next.next: slow=slow.next fast=fast.next.next return slow It was working for odd and even. submitted successfully in Leetcode. Its better to have fast and slow at the head. we cant keep on changing for different problems. In cyclic prob we had fast and slow at head. So its better to change the condition based on requirements.
@hoyinli7462
@hoyinli7462 3 жыл бұрын
excellent explanation. i love your diagrams
@mohammadusman9975
@mohammadusman9975 3 жыл бұрын
I saw the Robinhood logo and read it short list
@NeetCode
@NeetCode 3 жыл бұрын
lol, thats a better video idea
@maamounhajnajeeb209
@maamounhajnajeeb209 Жыл бұрын
you made it easy man, thanks
@henrydi800
@henrydi800 2 жыл бұрын
what will it return for tail=dummy=ListNdoe()? Why do we use dummy.next as a final return? Because I do not think the code modified anything for dummy.next
@prashantshukla8395
@prashantshukla8395 2 жыл бұрын
When we are writing tail=dummy=ListNode() we are creating a list with the first element as (0,-1, whatever, here they are automatically created as 0) and so,then the element that comes after that is added to tail.next.............and we are dummy.next to exclude that first element that we had initially created,if you don't do that you will end up with one or many(here many) 0 as new nodes... Hope it clears your query.
@manitbhusal1554
@manitbhusal1554 2 жыл бұрын
I've followed the same line of code, but I'm getting the problem of maximum recursion depth.
@JeremAl
@JeremAl 2 жыл бұрын
I think there is a mistake as pointed by YONAH GRAPHICS and fast should be set to head. Not head.next. I will test
@012345678952752
@012345678952752 2 жыл бұрын
@@JeremAl fast should point to head.next as mentioned in the video. It works for me. SO he might be have made some other mistake, because it shouldn't fail.
@tianjianni840
@tianjianni840 2 жыл бұрын
I forgot the base case (if not head or not head.next) and had the same issue. After adding that, problem of maximum recursion depth was fixed.
@Meloman0001
@Meloman0001 7 ай бұрын
Great explanation
@VirtualKnowledgeHub
@VirtualKnowledgeHub Жыл бұрын
Hello, Instead of listnodes, this code is returning the listnode object created at memory location. Please guide me, how to print entire listnode.
@dailyclipmafia5041
@dailyclipmafia5041 10 ай бұрын
no
@yuanthony5199
@yuanthony5199 2 жыл бұрын
Is this a constant space algorithm?
@juliuscecilia6005
@juliuscecilia6005 3 жыл бұрын
For getMid function, why was fast set to head.next? In Leetcode 876. Middle of the Linked List, fast was also set to head.
@ShubhamGupta-qk9uq
@ShubhamGupta-qk9uq 2 жыл бұрын
that is also fine as it will always give second middle number for even length LinkedList but as he said this solution assumes first one being the mid so it will cause recursion error if you go with head for fast.
@orangethemeow
@orangethemeow 2 жыл бұрын
I did it as slow, fast = head, head at first, I got an out of range error. No matter if you use head or head.next as initial value for fast, slow always stops at the same node
@veliea5160
@veliea5160 2 жыл бұрын
did you get why? I am curios why? now i need to memorize that this get_middle function is different than normal one
@DivyaSingh-bl4cj
@DivyaSingh-bl4cj 2 жыл бұрын
@@veliea5160 they both work in same manner of you see little more you will find out while condition in in both type of program is different . Fast, slow = heda,head While fast.next and fast.next.next ...... While loop difference both will return same thing .. it's just different way of writing
@ruiqiyin3847
@ruiqiyin3847 2 жыл бұрын
My understanding is that we want to find the node before right, so the node from getMid belongs to the right list.
@orangethemeow
@orangethemeow 2 жыл бұрын
When we define dummy and tail, how are they related to each other? Why do we not need to write dummy.next = tail? The code always works with or without that condition
@sanketgaikwad1399
@sanketgaikwad1399 2 жыл бұрын
dummy.next = tail is not written any where in code it actually dummy was only used to store the head for the sorted link list and primarily it was initalized with tail but tail kept on growing and last when we wanted to return head of the list we returned dummy.next
@vulamnguyen9453
@vulamnguyen9453 2 жыл бұрын
You can think it as "current_node" that we use to track the next node in linked list
@lucasxy
@lucasxy 2 жыл бұрын
so if you do dummy= Node(), tail = Node() separately, you need that condition dummy = tail. But in the code we do dummy= tail= Node(), that means we created 2 different pointers starting at the same Linked List Node. Then going forward dummy node stays at the starting points, but tail pointer keeps moving forward to the new node, adding new nodes to the LinkedList we created. When we do return dummy.next, we are basically returning the entire Linked List, but trimming the beginning dummy node, because this is not part of the list1 or list2.
@asdfasyakitori8514
@asdfasyakitori8514 2 жыл бұрын
This runs extremely slow in Golang, I don't understand
@AkramDevTalks
@AkramDevTalks Жыл бұрын
The recursive approach takes O(logN) space. Correct me if i am wrong
@yuriy6833
@yuriy6833 Жыл бұрын
thanks for explanation!
@yanhuichen8119
@yanhuichen8119 Жыл бұрын
Can someone explain why is the memory complexity logN? Appreciate!!!
@abdurrahmansinantokmak
@abdurrahmansinantokmak Жыл бұрын
Mergesort for array O(N) space and for linked list (log n) space.
@bandit8258
@bandit8258 Жыл бұрын
anyone know why do we need the "and" in the getMid function? Cant we use or? Thanks
@yiweikuang
@yiweikuang 10 ай бұрын
No. Since fast may be null, if we check fast.next, we will get an error java.lang.NullPointerException
@poorpanda9033
@poorpanda9033 Жыл бұрын
Thank you !
@AndrewCJXing
@AndrewCJXing 2 жыл бұрын
Could someone explain why we need a dummy? Can't we just use the tail variable and set it to null?
@012345678952752
@012345678952752 2 жыл бұрын
if you set tail = None, how would you set tail.next? You will get an error because a None object doesn't have "next" attribute. The ListNode object contains the "next" attribute. You use the dummy node because in the beginning, to assign smallest node as the first node, you need to check the 1st node of the left side and the 1st node of the right side. Whichever is smallest becomes tail.next.
@TURALOWEN
@TURALOWEN 2 жыл бұрын
thank you!!!
@ronpb3943
@ronpb3943 2 жыл бұрын
Thanks broooo
@edwardteach2
@edwardteach2 3 жыл бұрын
U a God
@hamaed19
@hamaed19 2 жыл бұрын
Nice
@heisenberg1844
@heisenberg1844 3 жыл бұрын
You are lit!
@mma-dost
@mma-dost 9 ай бұрын
How the hell people are able to understand the merge function man what's the use of dummy and tail ??
@JohannLiebert511
@JohannLiebert511 Жыл бұрын
java code: class Solution { public ListNode sortList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode left = head; ListNode right = getMid(head); ListNode tmp = right.next; right.next = null; right = tmp; left = sortList(left); right = sortList(right); return merge(left, right); } private ListNode getMid(ListNode head) { ListNode slow = head, fast = head; ListNode tmp = head; while (fast != null && fast.next != null) { tmp = slow; slow = slow.next; fast = fast.next.next; } return tmp; } private ListNode merge(ListNode list1, ListNode list2) { ListNode dummy = new ListNode(); ListNode tail = dummy; while (list1 != null && list2 != null) { if (list1.val < list2.val) { tail.next = list1; list1 = list1.next; } else { tail.next = list2; list2 = list2.next; } tail = tail.next; } if (list1 != null) { tail.next = list1; } else if (list2 != null) { tail.next = list2; } return dummy.next; } }
@eraytasay
@eraytasay Жыл бұрын
This code does not work. getMid() is wrong. It should be like this in Java: private static Node findMiddle(Node head) { var slow = head; var fast = head; while (fast.getNext() != null && fast.getNext().getNext() != null) { slow = slow.getNext(); fast = fast.getNext().getNext(); } return slow; }
@priyaaofficial7
@priyaaofficial7 9 ай бұрын
In Java it should be like .next to traverse basically you have to traverse first to get the mid Node not .getMid()
Learn Merge Sort in 13 minutes 🔪
13:45
Bro Code
Рет қаралды 341 М.
L26. Sort a Linked List | Merge Sort and Brute Force
22:11
take U forward
Рет қаралды 110 М.
1, 2, 3, 4, 5, 6, 7, 8, 9 🙈⚽️
00:46
Celine Dept
Рет қаралды 111 МЛН
LRU CACHE | LEETCODE 148 | PYTHON LINKED LIST SOLUTION
15:30
Cracking FAANG
Рет қаралды 842
LRU Cache - Twitch Interview Question - Leetcode 146
17:49
NeetCode
Рет қаралды 300 М.
Top K Frequent Elements - Bucket Sort - Leetcode 347 - Python
13:13
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 687 М.
Top 7 Algorithms for Coding Interviews Explained SIMPLY
21:22
Codebagel
Рет қаралды 442 М.
Merge Sort In Python Explained (With Example And Code)
13:35
FelixTechTips
Рет қаралды 225 М.
Maximal Square - Top Down Memoization - Leetcode 221
19:50
NeetCode
Рет қаралды 72 М.
5 Simple Steps for Solving Any Recursive Problem
21:03
Reducible
Рет қаралды 1,2 МЛН
I gave 127 interviews. Top 5 Algorithms they asked me.
8:36
Sahil & Sarra
Рет қаралды 673 М.