Тёмный

Remove Nth Node from End of List - Oracle Interview Question - Leetcode 19 

NeetCode
Подписаться 844 тыс.
Просмотров 192 тыс.
50% 1

Опубликовано:

 

25 окт 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 204   
@NeetCode
@NeetCode 3 года назад
Linked List Playlist: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-G0_I-ZF0S38.html
@johnpaul4301
@johnpaul4301 3 года назад
Why not just make the space between the left and right pointers n+1 instead of n? Then you wont need to create this dummy node
@vinaychaurasiya2206
@vinaychaurasiya2206 2 года назад
can you please show the solution by reverseing * which you were talking in starting please please
@Morimove
@Morimove Год назад
please include cpp and java solution also in every video it will be helpful
@msh104utube
@msh104utube 3 года назад
Hands down the best explanation I've seen...and it's in Python!
@DHAiRYA2801
@DHAiRYA2801 Год назад
Dummy node is actually not required if we run the loops till 'while right.next'. The reason we are using a dummy node is to handle the special case when we have to remove the first (head) node in a list of length 2
@evgeniyazarov4230
@evgeniyazarov4230 Год назад
Also, usage of 'while right.next' requires dealing with additional edge case when the list is empty, i.e. head=None. Not critical, but more elegant with dummy node
@a_k__
@a_k__ 10 месяцев назад
I was thinking if we change the condition of while to n=0 we won't need the dummy because then L will be n+1 steps behind R
@sun-ship
@sun-ship 9 месяцев назад
needs to be upvoted. not completely clear from the video.
@suvajitchakrabarty
@suvajitchakrabarty 8 месяцев назад
@@evgeniyazarov4230 Not really more elegant with dummy node. It sounds unnecessary and surplus to needs, actually @DHAiRYA2801 's solution makes more sense.
@leonlin41618
@leonlin41618 5 месяцев назад
# l, r pointer get n space l, r= head, head for _ in range(n): r = r.next # when case is delete the first node if not r: return head.next # l move to preTarget while r.next: l = l.next r = r.next l.next = l.next.next return head
@rossli8621
@rossli8621 2 года назад
To the point, concise, not bullshit. Your video deserves more rewards!
@dillondalton2989
@dillondalton2989 3 года назад
You'll be the reason I get my first SWE Internship
@gabbyamedu1485
@gabbyamedu1485 3 месяца назад
did u end up getting one :)
@ashishfargade1393
@ashishfargade1393 3 месяца назад
@@gabbyamedu1485 considering it was 3 years ago, I hope so
@Emorinken
@Emorinken Месяц назад
@@gabbyamedu1485I’ll get one, you can ask me, I’ll reply when i do
@chrischika7026
@chrischika7026 17 дней назад
have you
@gabbyamedu1485
@gabbyamedu1485 16 дней назад
@@chrischika7026 Hey, I hope you didn't think I was trying to be mean when I made that comment. I was just curious, not in a malicious way. And yes, I have received one. I hope you get one too or already have. Nice to see someone standing up for others, but I didn't mean it that way.
@priyanshmathur3010
@priyanshmathur3010 2 года назад
Upvoted it the moment you finished explaining and started coding..........Hats OFF........It's still fresh as in 2022
@Elise-n9f
@Elise-n9f 2 месяца назад
Thanks a ton!!💖 Since the condition is that '1
@shikhar2811
@shikhar2811 Год назад
Can be done in one while loop also: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: dummy = ListNode(0, head) first = dummy second = head while second: if n > 0: second = second.next n -= 1 else: second = second.next first = first.next first.next = first.next.next return head
@mostinho7
@mostinho7 2 года назад
Finding nth mode from the end of a linkedlist, can reverse the list and get a pointer, or can use two pointers, the space between them is n and move them forward at the same speed. When one reaches the end, the other will be at the nth element from the end
@nachiket9857
@nachiket9857 Год назад
The follow-up is that it should be done is one pass.
@yogeshgupta6094
@yogeshgupta6094 3 года назад
Great channel for programmers this channel has great potential....
@haphamdev2
@haphamdev2 5 месяцев назад
Thank you very much for your clear explanation. I really love NeetCode. One feedback: Instead of playing the youtube video on a popup, I think you can open RU-vid video directly when the "camera" button is clicked. It would be easier for me and other people to like the videos :D
@mr.anonymous6098
@mr.anonymous6098 2 года назад
Why do we need to create a dummy node? Can't we just return the head instead? When we return dummy.next, we essentially just return the head if I am not mistaken.
@PippyPappyPatterson
@PippyPappyPatterson 2 года назад
Try returning head on the given example case `linked_list = [1]` and `n = 1`. You'll see that you need a dummy node to delete a node in a linked_list of length 1.
@aniruddhashahapurkar9244
@aniruddhashahapurkar9244 Год назад
I literally smiled after learning about the trick here! Amazing!!!
@ChetanSingh-zp4ct
@ChetanSingh-zp4ct 2 года назад
I had a question, so instead of using dummy node can't we just put the condition where right node stops as soon as it reaches "right->next=NULL" in this way we can simply do left->next=y after that left->next=y->next, delete/free(y) ??
@orangethemeow
@orangethemeow 2 года назад
I thought about and tried that too. I guess no because the when there's only one node, the head will be removed as well
@abrarulhaqshaik
@abrarulhaqshaik 2 года назад
instead if asked n = 2, we can use n = 3 and solve, by doing so we would be behind by one node on left, we should handle edge cases for this approach, it would be when n = 1 and length = 1, then we should take care to return head.next
@jakenguyen2584
@jakenguyen2584 2 года назад
@@abrarulhaqshaik I tried this but I don't think it works because if the list size is 2, then None.next will cause an error.
@abrarulhaqshaik
@abrarulhaqshaik 2 года назад
@@jakenguyen2584 that is what I meant edge cases, handle that, and get done. It worked thats why I commented 💀
@linguisticgamer
@linguisticgamer 2 года назад
@@abrarulhaqshaik This is possible public ListNode removeNthFromEnd(ListNode head, int n) { if(head.next == null){ return null; } ListNode temp = head; for(int i = 0; i < n; i++){ temp = temp.next; } if(temp == null){ head = head.next; return head; } ListNode pre = head; while(temp.next != null){ pre = pre.next; temp = temp.next; } pre.next = pre.next.next; return head; }
@yunierperez2680
@yunierperez2680 8 месяцев назад
Loved how the Dummy head node technique removes the need to handle several edge cases, like when the nth node is the original head.
@ProfessorQuality
@ProfessorQuality Год назад
Managed to do this without looking at the solution, and thought mine was way more simple. Got 97.5% at 30ms. Basically count up the length of the linked list. Then use a while loop to keep track of the prev, current, and next nodes and drop the length by 1 until n is reached. Then set the prev.next to the current.next. Have to handle a few edge cases, but should just be O(n+n) -> O(n). Might be useful. Thanks for the videos! class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: length = 0 current = head prev = None # from end of list while current: length += 1 current = current.next current = head count = length while count >= n: if count == n: if prev: prev.next = current.next elif n == 1: head = None else: head = current.next else: prev = current current = current.next count -= 1 return head
@alihassanamin7854
@alihassanamin7854 11 месяцев назад
this will be slower by complexity. The leetcode time doesnt matter.
@ProfessorQuality
@ProfessorQuality 11 месяцев назад
@@alihassanamin7854 It could be slower (it isn't), but it wouldn't be due to complexity as O(2n) -> O(n) gives same time complexity.
@jrumac
@jrumac 8 месяцев назад
@@ProfessorQuality while your solution may simplify to O(n), the interviewer will likely follow up by asking for a single pass solution. good to know this as an optimal solution
@kewlv2k
@kewlv2k Месяц назад
@@jrumac The solution that neetcode provides is not single pass solution. He first moves the right pointer to the nth position, which in worst case could be O(n) and then moves the left pointer just before the nth postion which in the worst case could be O(n-1), which makes is O(2n) -> O(n). Same as @PorfessorQuality's solution
@WaldoTheWombat
@WaldoTheWombat 2 года назад
what do we need the dummy node for? why can't we just increase the difference between the left pointer and the right pointer by 1?
@reginatoronto
@reginatoronto 2 месяца назад
One word for you, the ultimate Leetcode boss I have ever seen
@KhayamGondal
@KhayamGondal 2 года назад
why not itterate over the the linked list once to get the length and then remove length - nth node? still time complexity O(N)?
@honeyjot8709
@honeyjot8709 8 месяцев назад
the question asks you to do it in single pass
@andreiflorea39
@andreiflorea39 4 месяца назад
I think it's time complexity O(n^2) because you could be removing the last node, iterating twice through the linked list. Once to get the length and once to remove it.
@kewlv2k
@kewlv2k Месяц назад
@@andreiflorea39 Iterating twice would mean O(n) + O(n), which is still O(n)
@andreiflorea1327
@andreiflorea1327 Месяц назад
@@kewlv2kyou’re right looking back idk what i was saying in that comment lol
@jeremydavidson7559
@jeremydavidson7559 25 дней назад
yes, this is the more intuitive approach, but less efficient/clean
@altusszawlowski4209
@altusszawlowski4209 10 месяцев назад
Great explanation! Instead of using a dummy we can just store prev of left and if left is None we can `return left.next` else we can `prev.next = prev.next.next`
@Amanda-bg7ib
@Amanda-bg7ib 2 месяца назад
really great explanation, better than other's ive seen
@samchopra100
@samchopra100 5 месяцев назад
Nice! Sir, I just love the way you explain the answers. I think we can also stop the iteration when R.next == nil so our L will be at position where we wanted. Then we won't need dummy node.
@kibi.mp4
@kibi.mp4 Год назад
Here's how I did it, hopefully this helps people understand this problem in a different way. It's different from the way shown in the video in that it is kind of a 2 pass solution where we first count the amount of nodes in the linked list and then do some simple math to figure out the amount of times we need to traverse the linked list on the second pass. Ultimately, your pointers end up on the node that is going to be "deleted" and on the node before it. This solution should boil down to O(N) time, but correct me if I'm wrong. # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: # assign dummy node before head node dummy = ListNode(0,head) # count nodes in LL lengthOfLL = 0 counterNode = head while counterNode != None: lengthOfLL += 1 counterNode = counterNode.next # calculate amount of times needed to traverse nodes moveTimes = lengthOfLL - n # assign node to delete and node behind deleteNode = head followNode = dummy # traverse linkedlist with the amount of times needed to move, decrement moveTimes while moveTimes > 0: deleteNode = deleteNode.next followNode = followNode.next moveTimes -= 1 # deleteNode pointer is now at the node that needs to be "deleted" # all we need to do now is set the node before it (followNode in this case) to the -.next # of the current node we are at (deleteNode) followNode.next = deleteNode.next # basically return the head node. return dummy.next
@Rajmanov
@Rajmanov Год назад
you are rigth but it's less optimized than the neecode solution.
@tomrod1949
@tomrod1949 Год назад
This was my approach as well, nice
@wingforce8530
@wingforce8530 Год назад
@@Rajmanov they are Nx2 vs. N + N, no difference at all
@racecarjonny8460
@racecarjonny8460 13 дней назад
@@wingforce8530 Sorry for replying to an old comment. The time complexity remains same for both the solution. But, if you check the follow up it asks you to do it in one pass.
@leonscander1431
@leonscander1431 3 месяца назад
I failed to solve previous problem (Reorder List). Learning the slow and fast pointer technique helped me to solve this one. It seemed like I need to use something similar. Right pointer ahead just tells us when the left is at appropriate node.
@hualiang2182
@hualiang2182 2 года назад
I wonder if we can do it without using an additional node. but with a tmp node keeping track of previous slow node. Leetcode has too many edge cases, hard to resolve.
@anandhu5082
@anandhu5082 3 года назад
thank you finally got it.... my thought process was like,,, if i need to remove the n-th node from end, i need to find, how far it is from start, then traverse from start to reach that node.. ahaha
@dumdum407
@dumdum407 6 месяцев назад
that's not a bad start tbh. Its still only 2 passes through the list, meaning O(2n) == O(n) ? or am I wrong on that.
@jordanb722
@jordanb722 4 месяца назад
@@dumdum407 Still twice as much work. It's one of those things that would be a drag on performance but rarely noticed because it won't blow up in production by being n^2.
@ryanwest8058
@ryanwest8058 3 года назад
Best explanation for this one I've seen, thanks
@gawi834
@gawi834 10 месяцев назад
Hats off to you my guy... The best explanation I've watched so far. You gained a new subscriber!
@samarmanjeshwar9665
@samarmanjeshwar9665 3 года назад
why have a dummy pointer when we can have left start at the first node, right start at (first + n)th node and run a loop until right.next == Null instead of right == Null?
@gururajchadaga
@gururajchadaga 3 года назад
or have right node at (first+n+1)th node.
@Andrew-dd2vf
@Andrew-dd2vf 2 года назад
This can run into problem in the edge case when n = # Nodes. Consider e.g. head=[1] and n=1. In that case using right.next==Null would return an error, because right itself would become Null after the first while loop in the code (where right is offset from left by n nodes). Using a dummy pointer will avoid this problem
@savbo_
@savbo_ 2 месяца назад
I think an easier way to do this is too find the position of N and delete it. One way to do this is too take the length of the llist and subtract N from it. This will give us the position. We iterate through again and once our current position is less than the target position ( len_llist - N), that we can connect the links accordingly. I don't know how much this makes sense writing it, but here is the solution I came up with: class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: ll_len = 0 curr = head while curr: ll_len += 1 curr = curr.next prev = None curr_pos = 0 target = ll_len - n # reset curr curr = head if ll_len == n: head = curr.next while curr and curr_pos < target: prev = curr curr = curr.next curr_pos += 1 if prev: prev.next = curr.next return head
@whiz-code
@whiz-code 5 месяцев назад
This is nice, with no further thought I have subscribed.
@linguisticgamer
@linguisticgamer 2 года назад
With 2 extra nodes only public ListNode removeNthFromEnd(ListNode head, int n) { if(head.next == null){ return null; } ListNode temp = head; for(int i = 0; i < n; i++){ temp = temp.next; } if(temp == null){ head = head.next; return head; } ListNode pre = head; while(temp.next != null){ pre = pre.next; temp = temp.next; } pre.next = pre.next.next; return head; }
@EurekaSe7en
@EurekaSe7en 3 года назад
Wow, I finally understand this. Thanks!
@wingforce8530
@wingforce8530 Год назад
but, what's the different from count the list size = N first then count it again for N - n? for both the solution , the time complexity are O(N)
@Stipruoliss
@Stipruoliss 7 месяцев назад
Nice, also you do not need to check if right is not null in the while loop 'while n > 0 and right:'. By definition if we start from head we know that the length is at least n so shifting by N is always possible.
@luiggymacias5735
@luiggymacias5735 7 месяцев назад
you can also solve it by checking the list length then que the position where is going to be removed and the iterate until the position before removed then we could move the next pointer to that pointer to be next.next that way the node is removed from the list like this: function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { let listSize = 0; let curr = head; while (curr) { listSize++; curr = curr.next; } if (n > listSize) { return head; } let dummy = new ListNode(head?.val) dummy.next = head let position = listSize - n; curr = dummy; for (let i = 0; i < position; i++) { curr = curr?.next; } curr.next = curr.next.next; return dummy.next }
@evlntnt1121
@evlntnt1121 8 месяцев назад
Can't we stop right pointer when the next to it is None (instead of right pointer itself is None)? This way we don't need dummy node
@edwardteach2
@edwardteach2 3 года назад
U a God: class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ dummy = slow = ListNode(0,head) fast = head for _ in range(n): fast = fast.next while fast: slow = slow.next fast = fast.next slow.next = slow.next.next return dummy.next
@dmitriylupych6505
@dmitriylupych6505 10 месяцев назад
Also we can check on each step if R_pointer.next is null, and then, L_pointer.next is a node to delete
@jaredrodriguez7576
@jaredrodriguez7576 3 года назад
super clear explanation of this! thank you so much
@symbol767
@symbol767 2 года назад
Took me a second to understand why you did left.next.next but wow, that is insane. Really good explanation, thank you
@DiptarajSen
@DiptarajSen Год назад
Can you please explain me that line left.next = left.next.next. Is it not going to fail when n is not 2? left.next.next is only going two nodes ahead. What if n was 3 ? Wouldnt it be then left.next.next.next?
@sidazhong2019
@sidazhong2019 3 месяца назад
@@DiptarajSen you need to remove 1 node. it's 2th node not 2 nodes.
@dilln2158
@dilln2158 2 года назад
This is a beautiful explanation, thank you
@nientranai1669
@nientranai1669 2 года назад
best explanation. really clear and neat
@amberbai9220
@amberbai9220 3 года назад
wow thank you for your clear explanation!! love it!
@Alex-yw7sn
@Alex-yw7sn 3 года назад
Thanks after your explanation, solution become easy understandable
@MP-ny3ep
@MP-ny3ep 7 месяцев назад
Amazing explanation !! Thank you!
@ladydimitrescu1155
@ladydimitrescu1155 Год назад
Super clever logic, Thanks for your explanation !
@frozendiaries3693
@frozendiaries3693 3 года назад
I understand the problem and I thought of the same thing. My problem was that I returned head instead of dummy.next cz it works for all the cases except one.
@saibharadwajvedula6793
@saibharadwajvedula6793 3 года назад
I did the same. I understand why it is so. Input: [1] 1 Output: [1] Expected: [] After removing the only node 1, the dummy(left) points to the null(right). If we return head, it returns 1, but 1 is not in our linked list anymore.
@anonymous-404
@anonymous-404 2 года назад
I did the same except I accounted for it with a condition i.e if left==dummy in the end that means the node to be deleted would be the head node therefore I return head.next in that case, hence it passed! if left==dummy: return head.next else: return head
@shashankdahake8985
@shashankdahake8985 7 месяцев назад
You are simply great man thanks for this.
@ravirajkakade12
@ravirajkakade12 Год назад
Very good explanation
@josephjoestar4318
@josephjoestar4318 Год назад
hmm, is there a reason no one is using a queue to hold the nth previous nodes? other then having to worry about a cyclic list, it seems it'd be faster perhaps.
@Unknownn716
@Unknownn716 Год назад
Hi, how did you use queue, are use it by : from queue import Queue ?
@josephjoestar4318
@josephjoestar4318 Год назад
@@Unknownn716 Yes from queue import x : if I want to be quick about it Somehow on leetcode, any solution that I use something from the queue collection has a super slow runtime. I get much faster runtimes if I implement my own queue with a linked list. You'd think using the LifoQueue would be faster then using a normal list since when the list size grows it has to be moved but I don't know. You can have the same code submitted to beating 99% and then if you re run it a minute later its only beating 3%. I can't make heads or tails :D
@JLJConglomeration
@JLJConglomeration Год назад
That would be O(n) time and O(n) space neetcode solution is O(n) time and O(1) space, and also addresses the followup one-pass requirement
@shreyghai8508
@shreyghai8508 8 месяцев назад
dont we have to remove the pointer of the desired node to remove from that node to the next one? for example say we have 1->2->3->4 and we want to remove 3. if thats the case, then we must have 2 point to 4. 1->2->4. However, wouldnt 3 be pointing to 4 still since we did not change that pointer?
@aayushgupta6914
@aayushgupta6914 2 года назад
I stored all the nodes in a list, and then just did a[-n - 1].next = a[-n].next, considering 'a' to be the list in which all the nodes were stored. This method takes only 1 pass, at the cost of n space.
@harshjain8753
@harshjain8753 2 года назад
bro that n space is ☠☠☠☠
@switchitup8893
@switchitup8893 Год назад
Thanks for great explaining
@bilalmohammad4242
@bilalmohammad4242 4 месяца назад
I love you man! ❤ Keep up the great work
@MohammadRizwan-hp2in
@MohammadRizwan-hp2in 2 года назад
Instead of dummy node you can also use another pointer following left pointer so when our left pointer is at nth node our following pointer is at the previous of nth node.
@danny65769
@danny65769 Год назад
In this approach, there'll be an edge case when nth node from the end is also first node.
@atulkumar-bb7vi
@atulkumar-bb7vi Год назад
Nice explanation and Thanks!
@glen6638
@glen6638 2 года назад
Clear explanation !👍
@martinemanuel8239
@martinemanuel8239 2 года назад
I hate python but every time that I see this type of videos, its not that bad , thnk u Neet
@AbhayNayak
@AbhayNayak 3 года назад
Nice job man, keep up!
@ChiCity511
@ChiCity511 2 года назад
Is there any time complexity difference between going through an array once with 2 pointers vs going through an array twice with 1 pointer? I solved this question by getting the length first and then iterating until length - n but I'm not sure if it's technically slower
@yskida5
@yskida5 Год назад
Technically slower since your time scales 2x as much w/ size of the input, but still O(n) time complexity Your approach is O(2n) which reduces -> O(n) since we don't care about coefficients for TC
@nitinullas
@nitinullas Год назад
@@yskida5 Both approaches are O(2n) . In fast and slow pointer approach, we are running 2 operations in one pass - one for fast and one for slow. In @3030's approach, we use 2 passes but use only one pointer to iterate. So both are equally efficient. I could be wrong but this is how I see it.
@guimauve522
@guimauve522 Год назад
@@nitinullas you are wrong, this is not how time complexity works. In this video it's O(n) because we only have 1 loop of length n, the 2 operations you are talking about are both O(1) so it doesn't make it O(2n)
@chrischika7026
@chrischika7026 17 дней назад
@@guimauve522 WRONG. it is O(2n). look (O(1) + O(1)) == O(2) , then O(2) * O(n) == O(2n). you dont know how time complexity works
@guimauve522
@guimauve522 13 дней назад
@@chrischika7026 Taken directly from the Big O Notation wikipedia article: "Multiplication by a constant Let k be a nonzero constant. Then O(|k|⋅g) = O(g)." So no I am not wrong and it is completly okay and even standard to remove all constant.
@premjeetprasad8676
@premjeetprasad8676 8 месяцев назад
Insted of checking for r=null can’t we check for r->next =null then we don’t need dummy node?
@keabrk
@keabrk 2 года назад
Thank you for the great explanation. Quick question. Could we set the distance between the two pointers to n+1 (3)? This solution would not require a dummy node.
@PIYUSH-lz1zq
@PIYUSH-lz1zq 2 года назад
Bro, what if there are null or 1 or 2 or 3 node only then ??
@axaxaxaxaxaxax33
@axaxaxaxaxaxax33 2 года назад
dummy node helps for when question wants you to remove the first (head) node
@tusharsingh4295
@tusharsingh4295 2 года назад
@@axaxaxaxaxaxax33 thanks had the same question
@lorenzoparas8689
@lorenzoparas8689 2 года назад
@@PIYUSH-lz1zq The question says that there can be at minimum 1 node, so there could be an if statement to handle the edge case for 1 node. 2 or 3 nodes can be handled by Kea's suggestion.
@Morimove
@Morimove Год назад
yes it can work but little complex so dummy will be good because it also include all cases
@abiz504
@abiz504 Год назад
thank you sir and am learning and getting better
@NeetCode
@NeetCode Год назад
Glad to be helpful! Best of luck
@nilkamalthakuria4030
@nilkamalthakuria4030 3 года назад
Thanks a lot! This is really helpful.
@jcb871
@jcb871 2 года назад
Why don't we count with one pass and reach the predecessor of correct node (count - n -1) in next pass? Really simple solution and still O(n).
@yugaank100
@yugaank100 Год назад
youll have to handle multiple edge cases. what if the (len == n), implying (count - n - 1) is -1
@JamesBond-mq7pd
@JamesBond-mq7pd 9 месяцев назад
wow. still don't understant how people came to this kind of solution. i used array to solve this problem.
@gao2737
@gao2737 2 месяца назад
in [1,2] case, when fast points to 2, why the program tells me that fast is null?
@radinak5872
@radinak5872 2 месяца назад
What if we were to parse the entire list into an array, then take the n from last? It does have more memory complexity but it is still O(n) for time.
@stefan.musarra
@stefan.musarra 4 месяца назад
If n > length, should this just return the list unmodified (the original head)? In the solution, if right reaches the end in the first while loop, then left will never be updated, and left.next = left.next.next will whack off the head. After the first while loop, I added if n > 0: return head
@leonscander1431
@leonscander1431 3 месяца назад
Read the problem constraints: The number of nodes in the list is sz. 1
@nicholassunga9115
@nicholassunga9115 2 месяца назад
`while n > 0 and right` - I think you can just use `while n > 0`
@dapoadedire
@dapoadedire 5 месяцев назад
So clear!!
@shahzebahmad7866
@shahzebahmad7866 2 года назад
Cant we find the size of the list which is O(n) and and do size-n this is also going to take us to the node which we want to delete..so the overall time complexity will be O(n+n) = O(n).
@gopalchavan306
@gopalchavan306 2 года назад
another approach would be to use recursion, where you start count when you react to last node and delete the node once n and count matches
@PippyPappyPatterson
@PippyPappyPatterson 2 года назад
@@gavinsweeney1554 i don't think it's double pass. It's basically a sliding window, so O(n) time.
@godekdominik2678
@godekdominik2678 2 месяца назад
Is this solution considered one-pass? I mean, in the worst case scenario (n = 1) L and R are going through the whole array individually.
@mathewkizhakkadathu3064
@mathewkizhakkadathu3064 2 года назад
Why is it when I keep a seperation of n nodes from the left to the right pointer I am guaranteed the left pointer will land on the node to be deleted when right pointer goes null?
@JLJConglomeration
@JLJConglomeration Год назад
is the 'and right' in the while loop condition necessary?
@spencersedano
@spencersedano Год назад
I was wondering if the n -= 1 is necessary.
@wallyyu5426
@wallyyu5426 2 года назад
Can use a for loop to set the right pointer
@Liteship
@Liteship 5 месяцев назад
very clever, how do you come up with such ideas?
@anasnasim8513
@anasnasim8513 13 дней назад
Here's what I did, completely different from the video but still is O(n) time complexity: # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: length = 0 current = head while current: length+= 1 current=current.next if n == length: return head.next current = head for _ in range(length - n - 1): current = current.next current.next = current.next.next return head I just calculated the length of the list and went to the length - n -1th element and disconnected it from the node. Lmk what you guys think!
@racecarjonny8460
@racecarjonny8460 13 дней назад
You solution works. But, have you checked the follow up? The follow up says, "can you do it in one pass?" If you have to do it in one pass, you have to take this approach.
@anasnasim8513
@anasnasim8513 13 дней назад
@@racecarjonny8460 Hmm yes. I did implement this later on.
@AbhishekYadav-vn2xj
@AbhishekYadav-vn2xj 2 года назад
C++ approach: class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* dummy = new ListNode(); dummy -> next = head; ListNode* left = dummy; ListNode* right = head; while(n>0 && right){ right = right -> next; n--; } while(right){ left = left -> next; right = right -> next; } //delete left -> next = left -> next -> next; return dummy->next; } };
@rahulchowdhury4227
@rahulchowdhury4227 Год назад
Can you tell me how the dummy Listnode is getting updated with latest left value, since it has not been explicitly updated
@rahulchowdhury4227
@rahulchowdhury4227 Год назад
or how head is getting updated
@Alexis-ym9ph
@Alexis-ym9ph Год назад
Two pointers approach is still 2 pass solution, but we are doing these passes simultaneously)
@aynuayex
@aynuayex 10 месяцев назад
i think we should properly remove the node to be removed by making its next pointer to none like this left.next.next, left.next = None, left.next.next this is without using a temp variable
@kartiksaini5619
@kartiksaini5619 2 года назад
Really love ur content but ur code won't work for list: [3] and 1 i.e it won't work if the nth value is same as that of the length of the list .. It's not capable of deleting head node....
@anjanov
@anjanov 2 года назад
I love you, thanks!
@zaph254
@zaph254 7 месяцев назад
No one is talking about how weird the algorithm is, I mean it works but I still can't understand the reason why right going out of the list will have left landed at the node that we want to delete
@MegaBeastro
@MegaBeastro 6 месяцев назад
because we shift right by n? n is the n'th node from the end of the list we want to remove
@hafiansari5881
@hafiansari5881 2 года назад
whats the difference between dummy.next and head in the return statement? As in why won't it work if you return head
@wenqianguo960
@wenqianguo960 2 года назад
if there's only one node in the linkedlist for example : [2], and we are deleting the 1st from the tail. The end result should be [].(empty linked list), since we need to remove head from the list. In this case, we need to return dummy.next to ensure the correct result.
@hafiansari5881
@hafiansari5881 2 года назад
@@wenqianguo960 ahhh makes sense thank you!
@wenqianguo960
@wenqianguo960 2 года назад
@@hafiansari5881 no problem! :))
@spencersedano
@spencersedano Год назад
dummy = ListNode(0,head) right = head Does this Linked List has 2 heads? How does the program know that the dummy ListNode is a placeholder?
@ravirajkakade12
@ravirajkakade12 Год назад
No... he created DummyNode and attached before head... DummyNode = new Node() DummyNode= head So list looks like DummyNode {val: null, next:head}
@cching2400
@cching2400 8 месяцев назад
Genius!
@swaroopkv4540
@swaroopkv4540 2 года назад
Do n-1 start from head both right n left pointer
@sparshnagpal1509
@sparshnagpal1509 2 года назад
Amazing!
@omi_naik
@omi_naik 3 года назад
why not do R->next ! = NULL so there would be no need to create a dummy node and we could start with the head.
@harshjain8753
@harshjain8753 2 года назад
fame just as name!!! you r awesome
@mohithadiyal6083
@mohithadiyal6083 3 года назад
Why not we change value of nth node from last to its next node value and point to none?
@sherifalaa5
@sherifalaa5 Год назад
I did it in one pass using a hash map, but I guess the space complexity was O(n)
@parikshitphukan635
@parikshitphukan635 2 года назад
you could just run the 2nd while loop till right.next instead of making a dummy node. Also, I am not sure if this covers the case of root node deletion
@smartpants6
@smartpants6 2 года назад
I believe that would return an error for left.next = left.next.next when there's only one element in the linked list, since left.next would be a none and there are no edges for a none.
@JohnIdlewood
@JohnIdlewood Год назад
If you use two pointers, does it count as one pass ? :D
@jeromeclaus5694
@jeromeclaus5694 3 года назад
Hello, I am new to coding, why can't I just use head.pop(len(head)-n)? It spits out the same answer. Thank you in advance for anyone that could help.
@abhinandannheggde1604
@abhinandannheggde1604 3 года назад
Nonetype object has no attribute next Left=left.next
@juliaschmidt3645
@juliaschmidt3645 Год назад
I've listened to your voice for so many hours now, but what's your name :D
Далее
Бокс - Финты Дмитрия Бивола
00:31
новое испытание
00:40
Просмотров 149 тыс.
Только ЕМУ это удалось
01:00
Просмотров 610 тыс.
I Solved 100 LeetCode Problems
13:11
Просмотров 165 тыс.
Coding Interviews Be Like
5:31
Просмотров 6 млн
FASTEST Way To Learn Coding and ACTUALLY Get A Job
10:44
LeetCode was HARD until I Learned these 15 Patterns
13:00
Making an Algorithm Faster
30:08
Просмотров 128 тыс.
How to NOT Fail a Technical Interview
8:26
Просмотров 1,5 млн
How I would learn Leetcode if I could start over
18:03
Просмотров 631 тыс.
Бокс - Финты Дмитрия Бивола
00:31