Тёмный

Floyd's cycle detection algorithm (Tortoise and hare) - Inside code 

Inside code
Подписаться 35 тыс.
Просмотров 63 тыс.
50% 1

Source code: gist.github.co...
🔴 Learn graph theory algorithms: inscod.com/gra...
⚙ Learn dynamic programming: inscod.com/dp_...
💡 Learn to solve popular coding interview problems: inscod.com/50p...
⌛ Learn time and space complexity analysis: inscod.com/com...
🔁 Learn recursion: inscod.com/rec...
NB: This video is ad-free, you can choose to support Inside code by purchasing one of the courses above or dropping a super thanks!
NB2: Discounts of courses above are permanent
I also post content on LinkedIn (inscod.com/lin...) and Instagram (inscod.com/ins...)

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

 

5 окт 2024

Поделиться:

Ссылка:

Скачать:

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

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 160   
@insidecode
@insidecode 2 года назад
Discover the new graph theory algorithms course: inscod.com/graphalgo 🔴 / \ 🔵-🔴 | | 🔴-🔵
@shivamsoam1419
@shivamsoam1419 3 года назад
That graphics requires a lot of work, TYSM👌👌
@insidecode
@insidecode 3 года назад
You're welcome!
@Lucas-md8gg
@Lucas-md8gg 4 месяца назад
Where did you do the graphs and animation? ​@@insidecode
@SauravC108
@SauravC108 Год назад
After meeting the hare, the rabit also slows down. Important point
@lolreach1627
@lolreach1627 Месяц назад
Awesome explanation! I believe another valid approach is to call the number of nodes from the head/start of the linked list till the node before the loop "x", but simplify and call the total number of nodes the slow pointer traversed inside the loop before encountering the fast pointer as "d", counting repeated ellements, so: total_distance_traversed_slow == x + d total_distance_traversed_fast == 2 * (x + d) When they encounter each other, it can be said the number of elements they traversed inside the loop, the "total distances minus x", are congruent modulo "loop_len" (the "loop" is analogous to a cyclic group of order/length "loop_len"): total_distance_traversed_slow - x === total_distance_traversed_fast - x (mod loop_len) d === x + 2 * d (mod loop_len) d + x === 0 (mod loop_len) Obviously, the element inside the loop that we end up on after traversing a distance of 0 inside the loop is the "head_loop" we want, which can also be reached if we traverse a distance congruent to 0, i.e., any multiple of "loop_len". Now, from simple modular arithmetic, if the slow and/or fast pointer were to traverse a distance of "x" more inside the loop, they would arrive at this "head_loop", since d + x === 0 (mod loop_len) (formally, "d", "2 * d + x", and "-x" belong to the congruence class of d modulo loop_len). So, a brilliant idea is to put either one of them at the start of the linked list and let them both progress one element at a time: once the pointer that we put at the start reaches "head_loop", they'll both have traversed the distance "x", which is also where they'll encounter each other, thanks to our previous reasoning, so we can check for that ("while(slow != fast) ...") without even needing to know the value of "x" beforehand (we can also rename the variables to make it very clear what is going on, say "pointer_inside_loop" and "pointer_from_start")! :D
@jonasbrooker5799
@jonasbrooker5799 3 года назад
You have a talent for clear and concise explanations. Thank you so much for this.
@insidecode
@insidecode 3 года назад
You're welcome!
@ggsingla
@ggsingla 2 года назад
This is the best explanation that I have found after discussing the same question with atleast 3 friends, they knew the approach but were not able to explain as clearly as this one
@vocipy2068
@vocipy2068 4 месяца назад
Giving the mathematical explanation for getting the entry point of cycle was the best part !
@joshuazhao7787
@joshuazhao7787 Месяц назад
Dude this is by far the best explanation for this I have ever seen. Hats off to you sir
@rajkishor6130
@rajkishor6130 11 месяцев назад
I've read numerous articles on this, but the algorithms always seemed confusing. However, your video provided a clear and concise explanation. Thank you so much for making it easy to understand
@praptib
@praptib 7 месяцев назад
Best channel I've come across for understanding algos clearly 💯
@sreenithisridharan6136
@sreenithisridharan6136 2 года назад
Great video with clear animations and explanations to about the internal logic behind the tortoise-hare algorithm, as well as how it can be used in the find the duplicate problem . Appreciate the effort
@niccolotoccane3041
@niccolotoccane3041 Год назад
Your approach of explaining algorithms is perfect, thank you very much for your videos
@youssefhussein3128
@youssefhussein3128 Год назад
This is the only video that I found, which explains why it specifically work in a reasonable way not just using slow and fast and make them met Thanks!❤
@_sky8068
@_sky8068 Год назад
After watching 10 videos , this was what made my day. Thanks
@falxie_
@falxie_ 2 года назад
Thank you for actually explaining how this works. I'm solving LeetCode 142 and I swear every video wouldn't actually explain *why* it works.
@expansivegymnast1020
@expansivegymnast1020 2 года назад
Doesn't get much better than this. If you're trying to understand this problem, go ahead and start here.
@nielslachat
@nielslachat Год назад
Brilliantly clear and visual explanation! Thank you very much!
@___vandanagupta___
@___vandanagupta___ 2 года назад
Your hard work really reflects in this video!!! Highly appreciate your talent, thanks a bunch for sharing it
@Pav298
@Pav298 3 года назад
This is the best explanation of why the second part of the algorithm works. I was confused why that was being assumed. It's a great trick to add to the mental toolbox! However, if processing is the bottleneck, hash tables may be preferred. This way the list is only scanned n times at most.
@NguyenNguyen-lm7dp
@NguyenNguyen-lm7dp Год назад
Amazing illustration to understand the solution
@RajaMuruganA
@RajaMuruganA 7 месяцев назад
Well Explained
@pk-ql6qu
@pk-ql6qu 3 месяца назад
these animations are bomb! Great job!
@Rishi-he7hs
@Rishi-he7hs 3 месяца назад
You can alsow think in terms of relative velocity From the point of view of slow pointer, fast pointer is moving 1 node ahead at a time So if finally fast pointer reaches the slow one, then definitely there is a cycle I think, using the similar approach if you move slow pointer n times forward and the fast one (n+1) times forward, that should also work
@Skryzer
@Skryzer Год назад
A few questions.. ..1st: Since fast enters the cycle earlier it's clear to me, why we need c1*l for the fast pointer. But slow will never make a lap before slow and fast meet, hence c2 is 0, isn't it? ..2nd: It's still not clear to me why we have to slow down fast for this to work. Doesn't slowing down fast break the whole equation we just formulated? Since c1 is the amount of laps fast did under the circumstances of fast being twice as fast as slow.
@sechabamotaung8552
@sechabamotaung8552 2 года назад
Amazing stuff. Helped me really understand the algorithm. Though I hope the rest of your videos are a bit clearer in audio.
@insidecode
@insidecode 2 года назад
Thanks, I'm working on it!
@عزالدينبنعبدالرحمن
Good explanation for the mathematical proof, Thank you.
@ahm3drn
@ahm3drn 2 года назад
This is literally the best explanation I came across while searching.. thanks a lot man
@insidecode
@insidecode 2 года назад
You're welcome
@waifjain4078
@waifjain4078 2 года назад
Excellent explanation. Thank you so much for the video.
@insidecode
@insidecode 2 года назад
You're welcome!
@yaswanthp2294
@yaswanthp2294 2 года назад
Floyd you genius
@lonelybookworm
@lonelybookworm 2 года назад
Thank you, this helped me further my understanding of how this works
@insidecode
@insidecode 2 года назад
You're welcome!
@arquier
@arquier 3 года назад
Again, interesting and super clear, thanks!
@insidecode
@insidecode 3 года назад
Thankd for your comment
@geezer2867
@geezer2867 2 года назад
thx bro, your video is extremly beautiful and clean, excellent!!
@insidecode
@insidecode 2 года назад
Glad it helped!
@grindinglcmeow
@grindinglcmeow 4 месяца назад
The math formula is straightforward but still, i'm like HOW DOES THEY JUST MEET when we do that starting point reset!
@andy2011go
@andy2011go 5 месяцев назад
Well explained! Thanks!
@ashishdukare1313
@ashishdukare1313 Год назад
Great animation...very easy to understand....Thanks
@jasopolis
@jasopolis 2 года назад
This is fantastic, thank you!!
@insidecode
@insidecode 2 года назад
You're welcome!
@LunaFlahy
@LunaFlahy Год назад
Awesome content! It's truly helpful to learn more about algorithms! :) Thank you for your contribution!
@youssifgamal2573
@youssifgamal2573 2 года назад
Finaly , what a great explanation , great job
@mehershrishtinigam5449
@mehershrishtinigam5449 3 года назад
This deserves more views!
@insidecode
@insidecode 3 года назад
Thanks! Help by sharing the video
@indraneel6601
@indraneel6601 Год назад
Gold mine video was just lit❤‍🔥
@someoneunknown2720
@someoneunknown2720 3 года назад
Great explanation. I solved using the first way. But I got a better one . Thanks 👍☺️
@insidecode
@insidecode 3 года назад
You're welcome!
@pavanbalu2734
@pavanbalu2734 3 месяца назад
I think, In the end code slow and fast should point to arr[0] instead of just 0
@amandapanda3750
@amandapanda3750 2 года назад
Thanks a lot , great explanation!
@insidecode
@insidecode 2 года назад
You're welcome!
@faithcyril513
@faithcyril513 Год назад
wowww, I wonder what went into initially developing this algorithm
@nikhilsinha2191
@nikhilsinha2191 2 года назад
This is where you know that math can solve anything without any issue
@anishbhandari4699
@anishbhandari4699 23 часа назад
In duplicate number 9th node should point to 2nd node not to 7th node
@willw4096
@willw4096 Год назад
really helpful visualization! thank you.
@insidecode
@insidecode Год назад
You’re welcome
@louistannudin2486
@louistannudin2486 3 года назад
This is amazing ! I can’t believe the details you put into this :o Also I think off an easier algo called cycle sort if we were to solve the find duplicate algo. I think that if the question was represented as a linked list then theres more merit to us rabbit vs turtle algo here. Thoughts ?
@louistannudin2486
@louistannudin2486 3 года назад
@@insidecode that is true! But thanks to the range from 1 to n it can be done in O(n), i dmed u on insta!
@milesl577
@milesl577 2 года назад
Great animation!
@insidecode
@insidecode 2 года назад
Thanks!
@roman_mf
@roman_mf Год назад
Great visuals and a very interesting algorithm. Subbed! But I want to join these asking about "x = ( c1 - 2c2 - 1) l + l - y" equation. I understand that (-1 * l) and +l will cancel each other out, so we're just using properties of math in here. But how one comes up with this idea? Is this just something that you learn to intuit?
@N3wW0rld
@N3wW0rld Год назад
I think yes, it's the sort of algebra "acrobatics" (or tricks) that you learn from others.
@khairulislamanik
@khairulislamanik Год назад
I believe Floyd himself didn't come up with this algorithm in a 30 minutes interview session 😀. It takes time to invent a brand new solution to a complex problem
@azurev2258
@azurev2258 Год назад
absolutely genius.
@EmekaUmeh1
@EmekaUmeh1 Год назад
Thank you!
@glowish1993
@glowish1993 2 года назад
i finally get it. thank you!
@Shambhabya_Medhi_
@Shambhabya_Medhi_ Год назад
thank you so much for making such videos
@anuragv400
@anuragv400 11 месяцев назад
great explanation man!
@RishikSinha-qc6yd
@RishikSinha-qc6yd 6 месяцев назад
Best content.. thanks. New subscriber now
@Dobby007
@Dobby007 2 года назад
This is the best explanation I've seen so far! But why is it implied that the fast pointer will always make c₃l loops before we slow it down? You showed that this is correct for yet another example of a linked list but isn't it the same as trying to prove a generalized case by proving more specific ones? I mean that two examples does not prove it yet. Probably one can find a really big loop with a really small tail. Will it still hold up? I guess yes, but why? And why do we even bother ourselves with slowing down the fast pointer? Couldn't it make it to the start of the loop with the previous step size (which is equal to 2 nodes at a time). I mean there's nothing in the formula that tells us to use a certain step size and c₃l + z distance can be passed with the same pace as well. Or not? To me c₃ is just some constant value which we introduced to replace the longer one: c₁ - 2c₂ -1
@insidecode
@insidecode 2 года назад
Hello, c3 is just another constant yes, c3 times l just means that fast will perform a certain amount of loops to kind of wait for slow, c3 can be 0, 1, 5, 1000... whatever, it depends on the length of the tail and the cycle. And examples were there just to show you what happens, the proof was done with the equations, we proved that x = c3l + z.
@insidecode
@insidecode 2 года назад
And for slowing down fast, it's because they must have the same speed, let me give you an example. We have two people walking towards a same position, and we know that they're at a same distance from that position, this is not enough to say that they will meet at that position, another condition is that they walk at the same speed. Same logic here, slow is at a distance x from the entry point of the cycle (what we're searching for), and fast is at a distance of c3l+z. And we proved that x = c3l+z, but it's not enough to know that they will meet at the entry point, they should also keep the same speed.
@Sumeet_100
@Sumeet_100 2 года назад
Absolutely incredible 😍
@NeoCodez
@NeoCodez Год назад
very helpful . thankyou
@helikopter1231
@helikopter1231 2 года назад
The degree of explanation is amazing!! but i have a couple of questions: 1 How did you decide to re-arrange the values in a linked list like this? why is 6(4) second for example and not 3? 2. .head isnt a method part of the list datatype though. What is llist here? When i do [1,3,4,4,5 ].head -- this is invalid. Would love if someone can explain! Thanks x
@insidecode
@insidecode 2 года назад
llist is of type LinkedList, check the code in description to see LinkedList definition
@QiZhou-yq5mo
@QiZhou-yq5mo Год назад
This is so helpful
@siddharthsingh3358
@siddharthsingh3358 Год назад
ure a freaking god man
@rishikeshpawar3230
@rishikeshpawar3230 Год назад
Thanks for video buddy.... :)
@joeharrison8571
@joeharrison8571 Год назад
brilliant stuff sir
@yulianloaiza
@yulianloaiza Год назад
Amazing! Thank you!!
@wardo5840
@wardo5840 3 года назад
Amazing explanation!
@insidecode
@insidecode 3 года назад
Thanks!
@Nao-Tomori
@Nao-Tomori 2 года назад
Can someone explain to me how " x = (c_1 - 2c_2)l - y" became "x = (c_1 - 2c_2 - 1)l + l - y"? Where did " - 1)l + l" were derived from?
@insidecode
@insidecode 2 года назад
Adding l and subtracting l doesn't change the equation, so by doing it we get x = (c1-2c2)l +l -l -y, and by taking the -l inside the parentheses it becomes -1 (because what's inside the parentheses is multiplied by l), so we get x = (c1-2c2-1)l +l -y
@yonahbyarugaba
@yonahbyarugaba 3 года назад
Thanks, man. This is incredible. My question is, what if one of the elements of the array was large, say, 200, but we know that this index doesn't exist because maybe n = 5. Now, let's say fast = 200; then array[ array[fast] ] = will be array[ array[200] ], which index is not present in the array. How is it dealing with this cause it works but I don't understand why
@insidecode
@insidecode 3 года назад
Having an element being equal to 200 while n is equal 5 means that the input is wrong, because the problem says that the array contains n+1 numbers all between 1 and n
@yonahgraphics
@yonahgraphics 3 года назад
@@insidecode Thanks for the reply, makes sense now!
@insidecode
@insidecode 3 года назад
@@yonahgraphics You're welcome!
@lamang8429
@lamang8429 9 месяцев назад
i lazy to comment (but i click like btn), but you are best in explanation, hat off.
@mybuddy11
@mybuddy11 3 года назад
very clear thanks you are number one, you are special from others
@insidecode
@insidecode 3 года назад
Thanks a lot!
@mybuddy11
@mybuddy11 3 года назад
@@insidecode however, you speak too fast, I'm not a native speaker I can't grasp it, I hope you speak more slowly
@insidecode
@insidecode 3 года назад
Ok thanks for telling me
@girish6064
@girish6064 8 месяцев назад
Thanks
@jazzyx95
@jazzyx95 Год назад
Why does fast and slower pointer eventually meets up in the cycle, I understand they traverse at different paces, but is there no situations where the fast pointer somehow always misses the slow pointer?
@praptib
@praptib 7 месяцев назад
imagine this like spinning planets, the faster a planet completes its revolution, the more often it can be spotted from the slower planet
@shyampraveensingh1958
@shyampraveensingh1958 3 года назад
Dude you are good!💯🔥
@insidecode
@insidecode 3 года назад
Thanks 🔥
@shyampraveensingh1958
@shyampraveensingh1958 3 года назад
@@insidecode make more videos 💯
@insidecode
@insidecode 3 года назад
I'm posting one every week, you can also follow me on Instagram where I also post content: @inside.code
@ashishburnwal1578
@ashishburnwal1578 2 года назад
keep up the good work
@Rajib317
@Rajib317 Год назад
C1, C2, C3 all are integers
@arianna6809
@arianna6809 2 месяца назад
@7:03 isn't it like this? slow traverses c3l+z and fast traverses x?
@70da24
@70da24 2 года назад
Awesome animations!
@insidecode
@insidecode 2 года назад
Thanks!
@hysoon6167
@hysoon6167 2 года назад
Great video! **just curious** which country are you from? I've never heard this accent before
@insidecode
@insidecode 2 года назад
Thanks! I'm from Algeria
@chiragkshatriya9486
@chiragkshatriya9486 2 года назад
Really great video sir. Was trying to understand the proof for a while, and the more read material on it, the more I got confused. So tried to watch many other videos, they helped a little but not fully, but after watching your video, it came intuitively to me. Thanks a lot. Amazing way of teaching.
@insidecode
@insidecode 2 года назад
You're welcome!
@vishnuvardhanreddy4841
@vishnuvardhanreddy4841 2 года назад
Thank you so much
@insidecode
@insidecode 2 года назад
You're welcome!
@samratpatel8060
@samratpatel8060 6 месяцев назад
any mathematical proof , why it works?
@gwendolensior7910
@gwendolensior7910 9 месяцев назад
how can I use the floyd's algo to search for hashes collisions ? Thanks for your help !
@arpit-jain
@arpit-jain 2 года назад
Can anyone explain how traversing and saving nodes in a set will identify cycle in a link list when there are multiple nodes with same value in linklist with out having any cycle? 00:40
@insidecode
@insidecode 2 года назад
Because linked list nodes are identified by their reference, which is unique, not by their value. You can for example in Python create an object and call id function on it like this id(object), you'll get as a result the id of that object
@arpit-jain
@arpit-jain 2 года назад
@@insidecode Thanks for quick reply. I got it now. At 00:40 set is containing only references and at 08:40 set is containing values.
@deniskim402
@deniskim402 2 года назад
THANK YOUUUUUUUU!!!!!!!!!!!!!!!!!
@dharaniidharkatikaneni4973
@dharaniidharkatikaneni4973 2 года назад
masterpiece
@caizza3
@caizza3 2 года назад
Amazing. Just amazing! How do you do these animations?
@insidecode
@insidecode 2 года назад
Hello, I use PowerPoint
@growmoreyt4192
@growmoreyt4192 Год назад
7:13 why you move the fast pointer only one step there?
@malokingi23
@malokingi23 Год назад
My brain is enthusiastically rejecting this whole idea 😞 I shall have to revisit this video next time I need to find a loop
@insidecode
@insidecode Год назад
haha, we're here if you didn't understand something
@malokingi23
@malokingi23 Год назад
@@insidecode I guess I just need to understand a specific proof of why exactly there will never be a list with a loop where the two pointers can skip each other for eternity.
@tyrodev5281
@tyrodev5281 2 года назад
Thanks!!
@THEAVISTER
@THEAVISTER 2 года назад
genius
@floyd99.99
@floyd99.99 2 года назад
if we take fast = arr[arr[slow]] instead of the fast = arr[arr[fast]]; if is way more faster
@insidecode
@insidecode 2 года назад
fast = arr[arr[slow]] would be wrong because fast would depend on the position of slow, which shouldn't be the case
@samuraijosh1595
@samuraijosh1595 6 месяцев назад
this is a math proof, i was expecting a more conceptual/intiuitive explanation before the proof.
@AjithKumaR-jw9wt
@AjithKumaR-jw9wt 2 года назад
5:48 x,=(c1-2c2-1)l+l-y pls explain this step
@zethembisogwala3475
@zethembisogwala3475 2 года назад
he added a - 1 inside the brackets multiplying l and then added l outside such that when you evaluate the brackets the - l cancels out the + l
@youssifgamal2573
@youssifgamal2573 2 года назад
I don't really understand this approach 8:55
@chandran-youtube
@chandran-youtube 2 года назад
🔥🔥🔥🔥🔥
@seongmoon6483
@seongmoon6483 2 года назад
Can someone explain 5:35? I do not understand how he got -1 and +l
@insidecode
@insidecode 2 года назад
We start by adding l and subtracting l, it doesn't change the expression, then we entered the -l inside parenthesis, it becomes -1 because what's inside the parenthesis will be multiplied by l
@seongmoon6483
@seongmoon6483 2 года назад
@@insidecode Took me a while but I got it. I remember one of the my smartest math professor do this now and it just felt like he was Doctor Strange. Thank for the video and the visuals are on point
@vasanthkumar-fq1ke
@vasanthkumar-fq1ke 2 года назад
what is happening here , x = ( c1 - 2c2 - 1) l + l - y ?
@AjithKumaR-jw9wt
@AjithKumaR-jw9wt 2 года назад
5:48 x,=(c1-2c2-1)l+l-y pls explain this step
@sujayshah5644
@sujayshah5644 2 года назад
we just re-write c1*L - 2*c2*L as : = c1 * L - 2 * c2 * L + 0 = c1 * L - 2 * c2 * L - L + L essentially we are writing + 0 as -L + L that way we can condense all the constants into a new constant c3 = (c1 - 2* c2 - 1 ) L + L - y = c3 L + y + z - y which becomes : = c3 * L + z
@zubairzafar480
@zubairzafar480 Год назад
Change your title to leetcode 287, I came here to understand that question.
@rimuru2483
@rimuru2483 2 года назад
gg bro
@nerd6134
@nerd6134 2 года назад
If u math videos you’ll get more views I bet
Далее
Cycle-Finding in Linked Lists
15:27
Просмотров 2,7 тыс.
would you eat this? #shorts
00:13
Просмотров 470 тыс.
Cheese grater HACK
00:22
Просмотров 1 млн
ВЫЖИЛ В ДРЕВНЕМ ЕГИПТЕ!
13:09
Просмотров 211 тыс.
Heaps, heapsort, and priority queues - Inside code
19:01
Programming Anime: Floyd's Algorithm Explained
19:44
Просмотров 268 тыс.
How I would learn Leetcode if I could start over
18:03
Просмотров 569 тыс.
Why Floyd's Cycle Detection algorithm works?
19:30
Просмотров 21 тыс.
The LeetCode Fallacy
6:08
Просмотров 529 тыс.
How to NOT Fail a Technical Interview
8:26
Просмотров 1,4 млн
If Programming Was An Anime
3:26
Просмотров 10 млн
would you eat this? #shorts
00:13
Просмотров 470 тыс.