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

Sdílet
Vložit
  • čas přidán 30. 07. 2021
  • Source code: gist.github.com/syphh/0c9286d...
    🔴 Learn graph theory algorithms: inscod.com/graphalgo
    ⚙ Learn dynamic programming: inscod.com/dp_course
    💡 Learn to solve popular coding interview problems: inscod.com/50problems_course
    ⌛ Learn time and space complexity analysis: inscod.com/complexity_course
    🔁 Learn recursion: inscod.com/recursion_course
    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/linkedin) and Instagram (inscod.com/instagram)
  • Věda a technologie

Komentáře • 156

  • @insidecode
    @insidecode  Před rokem +2

    Discover the new graph theory algorithms course: inscod.com/graphalgo
    🔴
    / \
    🔵-🔴
    | |
    🔴-🔵

  • @shivamsoam1419
    @shivamsoam1419 Před 2 lety +47

    That graphics requires a lot of work, TYSM👌👌

    • @insidecode
      @insidecode  Před 2 lety +3

      You're welcome!

    • @Lucas-md8gg
      @Lucas-md8gg Před měsícem

      Where did you do the graphs and animation? ​@@insidecode

  • @SauravC108
    @SauravC108 Před rokem +6

    After meeting the hare, the rabit also slows down. Important point

  • @vocipy2068
    @vocipy2068 Před měsícem +1

    Giving the mathematical explanation for getting the entry point of cycle was the best part !

  • @sreenithisridharan6136
    @sreenithisridharan6136 Před rokem +4

    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

  • @ggsingla
    @ggsingla Před 2 lety +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

  • @niccolotoccane3041
    @niccolotoccane3041 Před 10 měsíci +1

    Your approach of explaining algorithms is perfect, thank you very much for your videos

  • @praptib
    @praptib Před 4 měsíci +1

    Best channel I've come across for understanding algos clearly 💯

  • @rajkishor6130
    @rajkishor6130 Před 7 měsíci +5

    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

  • @youssefhussein3128
    @youssefhussein3128 Před rokem

    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!❤

  • @___vandanagupta___
    @___vandanagupta___ Před rokem

    Your hard work really reflects in this video!!! Highly appreciate your talent, thanks a bunch for sharing it

  • @nielslachat
    @nielslachat Před rokem

    Brilliantly clear and visual explanation! Thank you very much!

  • @_sky8068
    @_sky8068 Před rokem +1

    After watching 10 videos , this was what made my day. Thanks

  • @jonasbrooker5799
    @jonasbrooker5799 Před 2 lety +19

    You have a talent for clear and concise explanations. Thank you so much for this.

  • @NguyenNguyen-lm7dp
    @NguyenNguyen-lm7dp Před rokem

    Amazing illustration to understand the solution

  • @pk-ql6qu
    @pk-ql6qu Před 8 dny

    these animations are bomb! Great job!

  • @LunaFlahy
    @LunaFlahy Před rokem

    Awesome content! It's truly helpful to learn more about algorithms! :) Thank you for your contribution!

  • @falxie_
    @falxie_ Před rokem

    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.

  • @Skryzer
    @Skryzer Před rokem +1

    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.

  • @user-ir2lm7ye1x
    @user-ir2lm7ye1x Před rokem

    Good explanation for the mathematical proof, Thank you.

  • @youssifgamal2573
    @youssifgamal2573 Před 2 lety

    Finaly , what a great explanation , great job

  • @andy2011go
    @andy2011go Před 2 měsíci

    Well explained! Thanks!

  • @ashishdukare1313
    @ashishdukare1313 Před rokem

    Great animation...very easy to understand....Thanks

  • @Sumeet_100
    @Sumeet_100 Před rokem

    Absolutely incredible 😍

  • @Pav298
    @Pav298 Před 2 lety +1

    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.

  • @anuragv400
    @anuragv400 Před 8 měsíci

    great explanation man!

  • @lonelybookworm
    @lonelybookworm Před rokem

    Thank you, this helped me further my understanding of how this works

  • @waifjain4078
    @waifjain4078 Před 2 lety +1

    Excellent explanation. Thank you so much for the video.

  • @Rishi-he7hs
    @Rishi-he7hs Před 19 dny

    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

  • @user-dv5yh8dz7e
    @user-dv5yh8dz7e Před 4 měsíci +1

    Well Explained

  • @joeharrison8571
    @joeharrison8571 Před rokem

    brilliant stuff sir

  • @expansivegymnast1020
    @expansivegymnast1020 Před rokem

    Doesn't get much better than this. If you're trying to understand this problem, go ahead and start here.

  • @glowish1993
    @glowish1993 Před 2 lety

    i finally get it. thank you!

  • @grindinglcmeow
    @grindinglcmeow Před měsícem

    The math formula is straightforward but still, i'm like HOW DOES THEY JUST MEET when we do that starting point reset!

  • @yulianloaiza
    @yulianloaiza Před rokem

    Amazing! Thank you!!

  • @Shambhabya_Medhi_
    @Shambhabya_Medhi_ Před rokem

    thank you so much for making such videos

  • @arquier
    @arquier Před 2 lety +1

    Again, interesting and super clear, thanks!

  • @EmekaUmeh1
    @EmekaUmeh1 Před 11 měsíci

    Thank you!

  • @ahm3drn
    @ahm3drn Před rokem +2

    This is literally the best explanation I came across while searching.. thanks a lot man

  • @mehershrishtinigam5449

    This deserves more views!

    • @insidecode
      @insidecode  Před 2 lety +1

      Thanks! Help by sharing the video

  • @geezer2867
    @geezer2867 Před 2 lety +1

    thx bro, your video is extremly beautiful and clean, excellent!!

  • @jasopolis
    @jasopolis Před rokem +1

    This is fantastic, thank you!!

  • @indraneel6601
    @indraneel6601 Před rokem

    Gold mine video was just lit❤‍🔥

  • @azurev2258
    @azurev2258 Před 9 měsíci

    absolutely genius.

  • @willw4096
    @willw4096 Před 9 měsíci

    really helpful visualization! thank you.

  • @QiZhou-yq5mo
    @QiZhou-yq5mo Před rokem

    This is so helpful

  • @hazydimension
    @hazydimension Před rokem

    very helpful .
    thankyou

  • @yaswanthp2294
    @yaswanthp2294 Před rokem

    Floyd you genius

  • @pavanbalu2734
    @pavanbalu2734 Před 26 dny

    I think, In the end code slow and fast should point to arr[0] instead of just 0

  • @gwendolensior7910
    @gwendolensior7910 Před 5 měsíci

    how can I use the floyd's algo to search for hashes collisions ? Thanks for your help !

  • @ashishburnwal1578
    @ashishburnwal1578 Před 2 lety

    keep up the good work

  • @tyrodev5281
    @tyrodev5281 Před 2 lety

    Thanks!!

  • @RishikSinha-qc6yd
    @RishikSinha-qc6yd Před 3 měsíci

    Best content.. thanks. New subscriber now

  • @amandapanda3750
    @amandapanda3750 Před 2 lety +1

    Thanks a lot , great explanation!

  • @girish6064
    @girish6064 Před 5 měsíci

    Thanks

  • @wardo5840
    @wardo5840 Před 2 lety

    Amazing explanation!

  • @rishikeshpawar3230
    @rishikeshpawar3230 Před rokem

    Thanks for video buddy.... :)

  • @chiragkshatriya9486
    @chiragkshatriya9486 Před 2 lety

    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.

  • @sechabamotaung8552
    @sechabamotaung8552 Před 2 lety +5

    Amazing stuff. Helped me really understand the algorithm.
    Though I hope the rest of your videos are a bit clearer in audio.

  • @dharaniidharkatikaneni4973

    masterpiece

  • @growmoreyt4192
    @growmoreyt4192 Před 9 měsíci

    7:13 why you move the fast pointer only one step there?

  • @70da24
    @70da24 Před rokem

    Awesome animations!

  • @caizza3
    @caizza3 Před 2 lety

    Amazing. Just amazing! How do you do these animations?

  • @faithcyril513
    @faithcyril513 Před rokem

    wowww, I wonder what went into initially developing this algorithm

  • @someoneunknown2720
    @someoneunknown2720 Před 2 lety +1

    Great explanation. I solved using the first way. But I got a better one . Thanks 👍☺️

  • @milesl577
    @milesl577 Před rokem

    Great animation!

  • @deniskim402
    @deniskim402 Před rokem

    THANK YOUUUUUUUU!!!!!!!!!!!!!!!!!

  • @siddharthsingh3358
    @siddharthsingh3358 Před rokem

    ure a freaking god man

  • @mybuddy11
    @mybuddy11 Před 2 lety

    very clear thanks you are number one, you are special from others

    • @insidecode
      @insidecode  Před 2 lety

      Thanks a lot!

    • @mybuddy11
      @mybuddy11 Před 2 lety

      @@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  Před 2 lety

      Ok thanks for telling me

  • @roman_mf
    @roman_mf Před rokem +1

    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 Před rokem +1

      I think yes, it's the sort of algebra "acrobatics" (or tricks) that you learn from others.

    • @khairulislamanik
      @khairulislamanik Před 11 měsíci +1

      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

  • @vishnuvardhanreddy4841

    Thank you so much

  • @louistannudin2486
    @louistannudin2486 Před 2 lety +7

    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 Před 2 lety

      @@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!

  • @hysoon6167
    @hysoon6167 Před 2 lety

    Great video! **just curious** which country are you from? I've never heard this accent before

  • @jazzyx95
    @jazzyx95 Před rokem +1

    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 Před 4 měsíci

      imagine this like spinning planets, the faster a planet completes its revolution, the more often it can be spotted from the slower planet

  • @arpit-jain
    @arpit-jain Před 2 lety +1

    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  Před 2 lety

      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 Před 2 lety

      @@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.

  • @helikopter1231
    @helikopter1231 Před 2 lety +1

    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  Před 2 lety +1

      llist is of type LinkedList, check the code in description to see LinkedList definition

  • @Dobby007
    @Dobby007 Před 2 lety +1

    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  Před rokem +1

      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  Před rokem +1

      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.

  • @shyampraveensingh1958
    @shyampraveensingh1958 Před 2 lety +1

    Dude you are good!💯🔥

    • @insidecode
      @insidecode  Před 2 lety +2

      Thanks 🔥

    • @shyampraveensingh1958
      @shyampraveensingh1958 Před 2 lety

      @@insidecode make more videos 💯

    • @insidecode
      @insidecode  Před 2 lety +2

      I'm posting one every week, you can also follow me on Instagram where I also post content: @inside.code

  • @THEAVISTER
    @THEAVISTER Před 2 lety

    genius

  • @samratpatel8060
    @samratpatel8060 Před 3 měsíci

    any mathematical proof , why it works?

  • @nikhilsinha2191
    @nikhilsinha2191 Před rokem

    This is where you know that math can solve anything without any issue

  • @CHAN-xn9eq
    @CHAN-xn9eq Před 2 lety

    🔥🔥🔥🔥🔥

  • @Nao-Tomori
    @Nao-Tomori Před 2 lety

    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  Před 2 lety

      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

  • @lamang8429
    @lamang8429 Před 6 měsíci

    i lazy to comment (but i click like btn), but you are best in explanation, hat off.

  • @Rajib317
    @Rajib317 Před 9 měsíci

    C1, C2, C3 all are integers

  • @yonahbyarugaba
    @yonahbyarugaba Před 2 lety +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  Před 2 lety +5

      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 Před 2 lety

      @@insidecode Thanks for the reply, makes sense now!

    • @insidecode
      @insidecode  Před 2 lety +1

      @@yonahgraphics You're welcome!

  • @seongmoon6483
    @seongmoon6483 Před rokem

    Can someone explain 5:35? I do not understand how he got -1 and +l

    • @insidecode
      @insidecode  Před rokem

      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 Před rokem

      @@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

  • @AjithKumaR-jw9wt
    @AjithKumaR-jw9wt Před 2 lety

    5:48 x,=(c1-2c2-1)l+l-y pls explain this step

    • @zethembisogwala3475
      @zethembisogwala3475 Před 2 lety +1

      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

  • @user-eo3vm6oc4b
    @user-eo3vm6oc4b Před 2 lety

    if we take fast = arr[arr[slow]] instead of the fast = arr[arr[fast]]; if is way more faster

    • @insidecode
      @insidecode  Před rokem

      fast = arr[arr[slow]] would be wrong because fast would depend on the position of slow, which shouldn't be the case

  • @rimuru2483
    @rimuru2483 Před rokem

    gg bro

  • @vasanthkumar-fq1ke
    @vasanthkumar-fq1ke Před 2 lety

    what is happening here , x = ( c1 - 2c2 - 1) l + l - y ?

    • @AjithKumaR-jw9wt
      @AjithKumaR-jw9wt Před 2 lety

      5:48 x,=(c1-2c2-1)l+l-y pls explain this step

    • @sujayshah5644
      @sujayshah5644 Před 2 lety +4

      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

  • @matthewsama23
    @matthewsama23 Před rokem

    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  Před rokem

      haha, we're here if you didn't understand something

    • @matthewsama23
      @matthewsama23 Před rokem

      @@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.

  • @youssifgamal2573
    @youssifgamal2573 Před 2 lety

    I don't really understand this approach 8:55

  • @samuraijosh1595
    @samuraijosh1595 Před 3 měsíci

    this is a math proof, i was expecting a more conceptual/intiuitive explanation before the proof.

  • @zubairzafar480
    @zubairzafar480 Před rokem

    Change your title to leetcode 287, I came here to understand that question.

  • @lucasdiehl7384
    @lucasdiehl7384 Před 11 dny

    last example is useless other than in this toy example, almost never values translate to indices in a array(in bound).

  • @decostarkumar2562
    @decostarkumar2562 Před 3 měsíci

    What is the proof they will meet im loop?

  • @aimen__
    @aimen__ Před 2 lety +1

    Floyd Mayweather wela George Floyd

  • @nerd6134
    @nerd6134 Před 2 lety

    If u math videos you’ll get more views I bet

  • @siddharthsingh3358
    @siddharthsingh3358 Před rokem

    a f