Interview Question: Start of Loop in a Linked List

  Рет қаралды 143,546

Gaurav Sen

Gaurav Sen

7 жыл бұрын

This famous interview question is about reporting if a linked list has a loop, and then finding it's start. We use the 'Hare and Tortoise' approach, where two pointers moving at different speeds meet at surprising positions.
(Excellent) Answer Link by CEGRD:
stackoverflow.com/questions/29...
#linked-list #interview #puzzle

Пікірлер: 258
@shloksingh10
@shloksingh10 7 жыл бұрын
hey i have an alternate solution for finding head. after hare and tortoise meet. we will make hare pointer stop at that point and make tortoise pointer move till it reaches hare pointer again and count number on nodes. this will give us length of cycle. ( how many nodes are in cycle). lets denote dis with c. then just take 2 pointers p1 and p2 at c distance apart.. and move both at SAME speed till p1 and p2 meets. that point will be head.
@gkcs
@gkcs 7 жыл бұрын
Hey Shlok, this will also work. Nice alternative :-)
@futurezing
@futurezing 7 жыл бұрын
Nice alternative. IMHO, that would increase the constant of the algorithm and also the code complexity. If you don't care about these, then it works.
@udaysaiphanindra3138
@udaysaiphanindra3138 5 жыл бұрын
simple solution sir great
@bismeetsingh352
@bismeetsingh352 5 жыл бұрын
@@DheerajKumar-hr8bf They can point anywhere. Make p1 point to start of list for example and p2 c distance apart. github.com/BismeetSingh/linkedlistoperations Let me know if any mistakes found.
@abhinavporwal1476
@abhinavporwal1476 5 жыл бұрын
Hey, shlok . Thanks Man. Great Imagination!
@jaatharsh
@jaatharsh 4 жыл бұрын
in the end, he meant we get to the Starting point in the cycle since, Moving a Pointer from Head 'D' times = moving the pointer from the meeting point in cycle some constants times - K node Hence the solution works. Thanks, Gaurav this was really helpful.
@WilliamKurth
@WilliamKurth 5 жыл бұрын
If you get asked this question in an interview and instantly respond with Tortoise and Hare you’ll likely get another question. I think some people forget the goal of interviews questions is often to see how you solve a problem you don’t already know... that being said, this is one of the better explanations I’ve seen for this algo
@gkcs
@gkcs 5 жыл бұрын
Best to brush up on those acting skills then (Oh, find a loop in a linked list?! Gee, I wonder how....)
@deeproy7292
@deeproy7292 4 жыл бұрын
@@gkcs nice thought...
@sachinmaurya3259
@sachinmaurya3259 3 жыл бұрын
@@gkcs haha
@splendidbeaver2027
@splendidbeaver2027 Жыл бұрын
can you really end up figuring out haze and turtle by yourself for the first time you see this exercice ? I mean under pressure ?
@Marwan-oh4tk
@Marwan-oh4tk 8 ай бұрын
@@splendidbeaver2027 definitely not, lol!
@bitbyte8177
@bitbyte8177 4 жыл бұрын
Bro, I searched the whole internet to get the proof which I could understand. I wasted my two days in that search and couldn't find one which made sense to me or which I can sink the proof in. I watched your video twice. And I could finally sink it in. Thank you so much man! you saved me. Especially the last proof of how to make the pointers point to the starting node.
@TheHotdogstand
@TheHotdogstand 3 жыл бұрын
You're not only good at the CS part of things, you're also an amazing teacher! I kept asking a question in my head only to have you answer it right after. Thank you for this amazing lesson!
@gkcs
@gkcs 3 жыл бұрын
Thank you 😁
@AkshayKumar-mo9fk
@AkshayKumar-mo9fk 3 жыл бұрын
Thank god, finally someone explained the intuition behind this.. You're just amazing 🙌
@nitishvirtual4745
@nitishvirtual4745 Жыл бұрын
It was hard wrap my head around this concept. Thank you for making this video and providing with a detailed explanation.
@ayushraj-zb6sv
@ayushraj-zb6sv 2 жыл бұрын
most important thing is how to act like you have seen this question for first time in an interview :))
@AbrarShariar
@AbrarShariar 4 жыл бұрын
Love the energy of your teaching style!
@1096arvind
@1096arvind 4 жыл бұрын
Keep up the stellar work! This is some really useful stuff!!
@ananyamishra382
@ananyamishra382 8 ай бұрын
it is evident that he kept trying to understand why it works for a long time and then finally when he understood he was so happy❤
@AnushaTripathi
@AnushaTripathi 4 жыл бұрын
Awesome video! Thank you for explaining so clearly
@zeuszz6059
@zeuszz6059 3 жыл бұрын
Was stuck at this problem over a month, now i finally understand it, thanks a lot!!!
@jasonng3194
@jasonng3194 6 жыл бұрын
Thank you, this is a new concept to me
@jdelavega_
@jdelavega_ 4 жыл бұрын
That was a great explanation. Thx so much for the help! :-)
@natiatavtetrishvili3108
@natiatavtetrishvili3108 3 жыл бұрын
Loved this explanation, finally I fully understand how it works💡
@NohandleReqd
@NohandleReqd 4 жыл бұрын
Gaurav maaaan! I saw this question a few years back And couldn't understand the solution. This video helped! 😄. Thanks
@sathwikabhignan1862
@sathwikabhignan1862 2 ай бұрын
oh man, you are something else, fantastic explanation!!!
@tusharrawat1581
@tusharrawat1581 5 жыл бұрын
Cool !! That was a great explanation.
@anmolj
@anmolj 4 жыл бұрын
Thanks a lot, this video was really helpful!!
@juliolopezmontalvo
@juliolopezmontalvo 4 жыл бұрын
Finally someone explaining the math, thanks!
@pythoniccypress6715
@pythoniccypress6715 6 жыл бұрын
Great explanation!!
@shivangawasthi8750
@shivangawasthi8750 7 жыл бұрын
Hi Gaurav ,You nicely explained the explained the existance of solution for the equation but it can also be explained by the fact that if loop exist ,then when tortoise enter into the loop there are two particle in loop moving with different angular speed. So they have to meet at point. Relative angular speed is non zero constant so they must collide.
@gkcs
@gkcs 7 жыл бұрын
+Shiwang Awasthi Ah, yes that is true. A really good and intuitive observation. Thanks!
@shrishtychandra2003
@shrishtychandra2003 5 жыл бұрын
Exactly the explanation I wanted to know.
@gkcs
@gkcs 5 жыл бұрын
Thank you!
@laxminarayanchoudhary939
@laxminarayanchoudhary939 3 жыл бұрын
So,this was a interesting questions. I found a solution after couple of years.😁 At last excellent explaination.
@sakshamsingh6351
@sakshamsingh6351 4 жыл бұрын
watching it in 2020... deeply explained. thanks !
@bipul2138
@bipul2138 6 жыл бұрын
FINALLY GOT IT! THANKS
@inosuke44
@inosuke44 5 жыл бұрын
after watching it 3 times finally got it, now i can also explain it someone
@avikantsrivastava3489
@avikantsrivastava3489 3 жыл бұрын
Great explanation, love the intuition you give !!! Amazing content, love your channel. I will share this video with my Junior college-mates :)
@z08840
@z08840 3 жыл бұрын
...15 years ago it took me couple of hours to find this solution, though after some fiddling with analytical approach which was hard to interpret, finished with much easier graphical...
@divyatejaswinivengada6368
@divyatejaswinivengada6368 4 жыл бұрын
Freakin awesome man ! thank you !
@sandyhan4829
@sandyhan4829 4 жыл бұрын
I got it! Very clear. Thank you!
@chandrashakerreddy3915
@chandrashakerreddy3915 2 жыл бұрын
Coming here after going through two different sources , now I don't need to go any where because solution make sense to me now :) . Thanks for your efforts!!
@jabbukka
@jabbukka 5 жыл бұрын
Well explained! I didn't understand even though I read the solution but I totally got it with your video. Thank you :)
@gkcs
@gkcs 5 жыл бұрын
Glad to hear that 😁
@narinderkaur7506
@narinderkaur7506 2 жыл бұрын
Thanks a lot. This video help me understand the logic behind this.
@balajisv4052
@balajisv4052 5 жыл бұрын
Your explanation deserves an extra like! Great video bro
@gkcs
@gkcs 5 жыл бұрын
Thanks!
@ankithas1868
@ankithas1868 2 жыл бұрын
Awesome Explanation !!
@shanbocheng9462
@shanbocheng9462 4 жыл бұрын
Great explanation with the equations
@mayukhchatterjee4863
@mayukhchatterjee4863 4 жыл бұрын
Excellent Explanation. Keep up the good work man...!
@pintunag
@pintunag 5 жыл бұрын
start with fast and slow pointers. When slow meets fast, stop. Take a pointer p1, now assign head to p1. Move p1 by one position and slow by one position till p1 and slow meet. By the way, slow and p1 will meet exactly at the start of the loop.
@deepakchoudhary2970
@deepakchoudhary2970 7 ай бұрын
Man this is wonderful, I was so stuck in this problem, went through multiple videos but finally found the perfect explanation. Thanks a ton, Gaurav.
@gkcs
@gkcs 7 ай бұрын
You're welcome!
@vivekpathak3643
@vivekpathak3643 Жыл бұрын
thankyou for this much needed explanation.
@kasturikakatkar
@kasturikakatkar 3 жыл бұрын
Thank you for this video
@stalera
@stalera 5 жыл бұрын
very well explained!
@gkcs
@gkcs 5 жыл бұрын
Thanks!
@klausdupont6335
@klausdupont6335 3 жыл бұрын
The -K part really hits the point! Nice work!
@ivantishchenko4686
@ivantishchenko4686 4 жыл бұрын
Great video. Thanks for sharing!
@gkcs
@gkcs 4 жыл бұрын
Thanks 😊
@SugamMaheshwari
@SugamMaheshwari 3 жыл бұрын
Beautiful Explanation Brother !!!
@mrnobodyy96
@mrnobodyy96 Жыл бұрын
Very good explanation. Thanks!
@gkcs
@gkcs Жыл бұрын
Thank you!
@anmolmishra990
@anmolmishra990 7 жыл бұрын
Such a nice explanation D+K part was explained so nicely, thanks bhaiya
@SurajKumar-bw9oi
@SurajKumar-bw9oi 4 жыл бұрын
Watch it twice to get the intuition :')
@mohd.rajeen4256
@mohd.rajeen4256 3 жыл бұрын
awesome explanation !!
@amitpurohit8816
@amitpurohit8816 Жыл бұрын
9:00 this was the missing link I was looking for! Thanks Gaurav bhai for this explanation!!!
@vaibhavsingh1157
@vaibhavsingh1157 6 жыл бұрын
Your explanation proves that from the meeting point i.e. c(j - 2i) it falls 'k' short to reach the intersection point, but it doesn't prove that from the meeting point it will take 'D' to reach the intersection point. I think what is missing over here is you will have to prove 'j-2i' is always equal to 1.
@nirbhaysingh5440
@nirbhaysingh5440 3 жыл бұрын
I think if it is not equal to 1 then it will end up in a never-ending loop as they are moving at the same speed. Any thoughts? @Gaurav Sen
@narendra570
@narendra570 7 жыл бұрын
U are really good at explaining things :)
@gkcs
@gkcs 7 жыл бұрын
Thanks!
@ankushreddy9789
@ankushreddy9789 2 жыл бұрын
atlast someone explained the algorithm with proof. amazing work.
@mrfrog20110607
@mrfrog20110607 6 жыл бұрын
Thank you so much! Your explanation is excellent! Really helps me a lot understanding the question!
@gkcs
@gkcs 6 жыл бұрын
Thanks!
@akshaytata
@akshaytata 5 жыл бұрын
Lovely explanation. Thank you
@rakeshsinha9541
@rakeshsinha9541 4 жыл бұрын
Thanks for the mathematical proof but test case which includes a whole circular linked list requires slight change in finding the start of the loop ie. head
@NoopDawg
@NoopDawg 2 жыл бұрын
How do you compare nodes in a cyclic graph though? In the final solution it seems like you need to start a pointer at the head (hptr) and at the meeting point (mptr), move forward by 1 and then check if hptr == mptr. how would the linked list implementation handle that? memory location or following the nodes?
@vaibhav8257
@vaibhav8257 2 жыл бұрын
thanks for explanation 😃
@adityatiwari1022
@adityatiwari1022 4 жыл бұрын
The first question they ask in any damn interview.
@utkarshbansal1312
@utkarshbansal1312 4 жыл бұрын
great work man. Keep doing. 👍👍👍👍👍👍👍
@walterwhite6068
@walterwhite6068 5 жыл бұрын
Excellent explanation
@rishabhpandey3456
@rishabhpandey3456 2 жыл бұрын
Thank You Sir.
@chodingninjas7415
@chodingninjas7415 4 жыл бұрын
great explanation
@anuragsekhri2315
@anuragsekhri2315 2 жыл бұрын
finally understood the logic thanks
@jyotiranjan32
@jyotiranjan32 3 жыл бұрын
When ever we are choosing the slow pointer and fast pointer how fast they should move(can slow pointer move twice and fast pointer move three times .How we should decide.)
@user-oy4kf5wr8l
@user-oy4kf5wr8l 3 жыл бұрын
Thanks buddy!
@sergemerto256
@sergemerto256 Жыл бұрын
No need to add maths equations too. Consider a very large cycle so that the first pointer when it reaches the starting node of the cycle is t distance behind the fast pointer. That means that fast pointer is (c-t) distance behind the first to catch up with it. So, we have (c-t) + y = 2y assuming at y nodes far away the both will meet. so y = (c-t) or in other words, the meeting point is at distance c from the head pointer. So now just take head and slow pointer(at the meeting point) and keep doing ->next until they both coincide. That will be the answer.
@kanwarudaysingh
@kanwarudaysingh 7 жыл бұрын
Hi Gaurav, Nice explanation. But you needed to say that k=(j-2i)x-D, so the slow pointer is at D iterations short of a cycle. So just by iterating it D number of time, we can get to the beginning
@mrnobodyy96
@mrnobodyy96 6 жыл бұрын
You are wrong.
@mojojojo1211
@mojojojo1211 3 жыл бұрын
Could someone please point me to the link of an implementation for this
@ahskid2695
@ahskid2695 4 жыл бұрын
Well explained :)
@YashRaithatha1989
@YashRaithatha1989 4 жыл бұрын
If space complexity is not an issue, we can iterate the loop till it reaches null and keep checking each node in HashSet. If a node doesn't exist then add it to HashSet and if it exists then break the loop and return that node which is the start of loop. To find length of the loop, we can keep extra Stack where we push the node while iterating until we discover the starting node of the loop as mentioned above. Then keep popping the nodes from the stack until we get the starting node and keep a counter while popping which is the length of the loop.
@umangjain3875
@umangjain3875 4 жыл бұрын
WOW, Thanks Gaurav
@raj_patel_43
@raj_patel_43 4 жыл бұрын
Thanks man
@uneq9589
@uneq9589 5 жыл бұрын
Gotcha! I had to re-watch, but got it finally.
@gkcs
@gkcs 5 жыл бұрын
Awesome!
@uneq9589
@uneq9589 5 жыл бұрын
@@gkcs Hi Gaurav, can you make videos on the problem www.interviewbit.com/problems/matrix-median/ and system design of a voting system?
@deeproy7292
@deeproy7292 4 жыл бұрын
same here bro
@JeesuByun
@JeesuByun 2 жыл бұрын
great explanation. Written explanations out there are hard to understand. nice job!
@ABugWithTheBigDreams
@ABugWithTheBigDreams 5 жыл бұрын
i didnt understand what there is fallshort ?
@nareshupadhyay1192
@nareshupadhyay1192 3 жыл бұрын
Thanks a lot Gaurav Bhai
@pickarpit
@pickarpit 7 жыл бұрын
Nicely Explained! :)
@gkcs
@gkcs 7 жыл бұрын
Thanks!
@ShivamSinghNIT
@ShivamSinghNIT 5 жыл бұрын
Don't you think the distance k should represent distance from 2 to 4 instead of 3 to 4? Otherwise, the equation itself will not be right. Moreover, when you say, in the end, that we would be 'k' short that means from the meeting point we would go back to 3 not 2, correct?
@_overide
@_overide 4 жыл бұрын
Awesome explanation Gaurav!
@sunilkumar-ik9ib
@sunilkumar-ik9ib 5 жыл бұрын
Thank you Gaurav.
@gkcs
@gkcs 5 жыл бұрын
😁
@yashdixit3352
@yashdixit3352 2 жыл бұрын
Awesome!
@sarfarazalam6077
@sarfarazalam6077 5 жыл бұрын
Thanks !!
@gkcs
@gkcs 5 жыл бұрын
Thank you!
@lallu12343
@lallu12343 5 жыл бұрын
I would have known the solution posted by @shlok singh But your solution is smarter and shorter. I will keep this in mind.
@vaibhavkarn6884
@vaibhavkarn6884 3 ай бұрын
Best Explanation. Thanks Gaurav for this. 1) At the meeting point one pointer that starts from start covers D. 2) Now at the same point when the next pointer start from meeting point trying to travel D, It will cover N*(circle Length) - k. so from the point it started at will be k steps before. And k steps before is actually the meeting point. So they both will meet at the meeting point.
@saswataacharya5431
@saswataacharya5431 2 жыл бұрын
Great Explanation Sir
@bhavukgarg3619
@bhavukgarg3619 5 жыл бұрын
nice explanation bro.
@niharikaepuri3305
@niharikaepuri3305 7 жыл бұрын
If we start the pointer at the start and one at the meeting point and move them by D+K then both end up at the same place? Can you be more specific around 8:05 to 8:12
@gkcs
@gkcs 7 жыл бұрын
We end up at the same place, which is the meeting point, if we move the pointers from the start and meeting point respectively. The reason for this is D+K is where the meeting point is. Also, we see that D+K is a multiple of C, so any pointer inside the circle when moved by D+K nodes will revolve to the same place. Thats because moving a distance divisible by C is like taking a few cycles around the loop.
@sachinbhandari345
@sachinbhandari345 5 жыл бұрын
We can explain it even simpler if we set the starting of loop at the head node( the starting node). And then make it complex by adding the nodes at the starting point.
@AbhishekKumar-wx3rw
@AbhishekKumar-wx3rw Жыл бұрын
very nice explanation tank you
@ChiCity511
@ChiCity511 7 жыл бұрын
At around 3:45 why does n need the c and i variables? Doesn't the tortoise never make it through a full cycle since the hair would intersect it before that happens?
@gkcs
@gkcs 7 жыл бұрын
+TrollkimNoah That might be true. But in the worst case, the tortoise and hare will meet at the start of the circle. Assume the whole graph to be a circular list. Then the tortoise makes 1 revolution and the hare makes 2.
@sumeetsuryawanshi8384
@sumeetsuryawanshi8384 4 жыл бұрын
Thank u gaurav ...👍
@kollisashank1465
@kollisashank1465 6 жыл бұрын
Hey Gaurav, let's say that if the question asked was to find out start point of the loop. How is this algorithm efficient than hashing? hashing would always take O(N) space and run time is O(N). but this algorithm runtime can be more than O(N).. but I agree that this will always take a constant space O(1). Just trying to understanding which one is better?
@gkcs
@gkcs 6 жыл бұрын
This algorithm has a run time of O(N) actually. The loop will have both pointers touching inside within 2 rounds. Thats because the gcd of (loop length and 2) is atmost 2. This question is usually asked to test a candidate's resourcefulness. Hashing is the practical approach, but this works better in interviews 😊
@kollisashank1465
@kollisashank1465 6 жыл бұрын
thanks Gaurav - This GCD info helps..
@sciphilo754
@sciphilo754 6 жыл бұрын
Hey man, could you please explain the reasoning behind the GCD concept " The loop will have both pointers touching inside within 2 rounds. Thats because the gcd of (loop length and 2) is atmost 2". Or could you post a link where I can learn about it?
@gkcs
@gkcs 6 жыл бұрын
It's not mentioned anywhere I think...here is another video which might help with the intuition: kzfaq.info/get/bejne/epN0jNeG0rixkWg.html
@saketkumar7335
@saketkumar7335 3 жыл бұрын
the equation that you figured out at 4:36 th sec that is N=C*(j-i). Does it mean that walking for some value of N (where n is D+K+C(i)) steps is same as making few complete cyclic loops ?
@arihantsingla1212
@arihantsingla1212 4 жыл бұрын
whats time complexity of this solution?
@prateekjhabak5414
@prateekjhabak5414 4 жыл бұрын
Nice explanation and logic deduction Gaurav_Sen..!!
@Stoic623
@Stoic623 4 жыл бұрын
Hi Gaurav, Alternative code for finding the starting node of linked list cycle. Please let me know if there are any issues. if (loopExist) { slwPtr = slwPtr.next; List list = new ArrayList(); while (slwPtr != fstPtr) { list.add(slwPtr); slwPtr = slwPtr.next; } slwPtr = head; while (slwPtr != fstPtr) { if (list.contains(slwPtr)) { return slwPtr; } slwPtr = slwPtr.next; } } start = slwPtr; return start;
@gkcs
@gkcs 4 жыл бұрын
Nice try but no. No auxiliary space. That extra list used won't be allowed 🥺
@prernagolani9014
@prernagolani9014 3 жыл бұрын
nice explaination
@mayukhchatterjee4863
@mayukhchatterjee4863 4 жыл бұрын
I have a question. How are we going to compute the length D? Because if we dont we cannot stop the pointer P1.
Why Floyd's Cycle Detection algorithm works?
19:30
Dinesh Varyani
Рет қаралды 20 М.
No empty
00:35
Mamasoboliha
Рет қаралды 10 МЛН
What it feels like cleaning up after a toddler.
00:40
Daniel LaBelle
Рет қаралды 92 МЛН
Smart Sigma Kid #funny #sigma #comedy
00:40
CRAZY GREAPA
Рет қаралды 33 МЛН
Whiteboard Coding Interviews: 6 Steps to Solve Any Problem
15:18
Fullstack Academy
Рет қаралды 364 М.
Why Floyd's cycle detection algorithm works? Detecting loop in a linked list.
24:11
Vivekanand Khyade - Algorithm Every Day
Рет қаралды 113 М.
Amazon Coding Interview Question - Recursive Staircase Problem
20:01
What is a MESSAGE QUEUE and Where is it used?
9:59
Gaurav Sen
Рет қаралды 959 М.
I gave 127 interviews. Top 5 Algorithms they asked me.
8:36
Sahil & Sarra
Рет қаралды 633 М.
What is an API and how do you design it? 🗒️✅
15:26
Gaurav Sen
Рет қаралды 721 М.
25 Nooby Pandas Coding Mistakes You Should NEVER make.
11:30
Rob Mulla
Рет қаралды 265 М.