FIND THE STARTING POINT OF THE CYCLE | Knowing Algorithm is Okay, But Knowing The Intuition Matters

Поділитися
Вставка
  • Опубліковано 17 гру 2024

КОМЕНТАРІ • 172

  • @takeUforward
    @takeUforward  4 роки тому +18

    C++ Solution: github.com/striver79/SDESheet/blob/main/detectStartOfLoop_C%2B%2B
    Java Solution: github.com/striver79/SDESheet/blob/main/detectStartofLoop_Java
    Do check me at Instagram(Striver_79) to know all about the success stories, and attend the live interactions that I keep doing :)

    • @PriyanshuKumar-bx9oy
      @PriyanshuKumar-bx9oy Рік тому

      Sorry but I didn't understood how you have written L1=nc-L2 ?

    • @anuragshekhawat
      @anuragshekhawat Рік тому

      Slow pointer can never make more than two turns in loop.

    • @anuragshekhawat
      @anuragshekhawat Рік тому

      At any point if slow pointer enters loop, after travelling half distance of loop, slow pointer bound to meet fast. I am assuming slow pointer takes 1 step and fast takes two steps.

  • @shubhamjain54519
    @shubhamjain54519 11 місяців тому +1

    5:30 optimized approach tortoise hare
    7:50 step2
    10:20 intuition/proof
    14:10 code

  • @allmighty2000
    @allmighty2000 4 роки тому +35

    intuition that When I first heard that we can’t use a hash table ,
    The first thing came at my mind , it’s like A is a person he is going into a forest , roaming around , and then he observed that he is lost by remembering that he just visited that place , but we are told not to use hash table ,
    So it’s just like A is a person with memory loss , so let’s assume B is his brother he also come the same way to find his brother but he will be also lost too ,
    And their speed must differ so that they find out each other (collide)
    But I thought my idea is wrong as it’s not possible to calculate their starting position by collision theory ,
    Now I am seeing , that don’t be lazy imaging , just grab pen and paper and do some work to find out relations ,
    @Raj bhaia thanks 🙏

  • @vijaykumar-b6i7t
    @vijaykumar-b6i7t 5 місяців тому +2

    @takeUforward hii, i think there is a slight change in the intution equation. it should be like 2(l1+l2+k(c) )=l1+l2+n(c). because pointers are not bound to collide in the first iteration it self that you mentioned in the video but was missing in the equation, writing the equation in this way seems better to me. overall its good, and thanks for the playlist, it's wonderful.

    • @abhinavbhar645
      @abhinavbhar645 3 місяці тому

      this needs more likes
      so it goes up

  • @abhay9994
    @abhay9994 Рік тому +1

    Dear Striver,
    I wanted to send you a heartfelt thank you for your tireless dedication to teaching DSA for free. Your selflessness and passion for helping students with their job interview preparation have made a significant impact on my life and countless others. I am incredibly grateful for the knowledge and confidence you have imparted to us. Thank you for everything you do!

  • @LeetDaily
    @LeetDaily 3 роки тому +9

    instead of nC we may write 1 cycle because as fast pointer completes two cycles slow pointer will complete atleast one and that we are adding in L2.....

  • @AZ-kh9ex
    @AZ-kh9ex 4 роки тому +123

    Irony is none of those 7* or red coders would have ever joined such a subscription plan ( as unacademy's ) to reach where they are ...

    • @amanshrivastava908
      @amanshrivastava908 3 роки тому +6

      Yeah Striver himself claimed in his latest course related Cp course post he learned everything googling and finding online tutorials. These course is for those people who can't go without spoonfeeding and cannot self learn from themselves

    • @aryanverma7800
      @aryanverma7800 3 роки тому +11

      @@amanshrivastava908 there is something called time buddy

  • @kaustav07
    @kaustav07 4 роки тому +6

    Finally the intuition is clear.

  • @subhamrajgarhia2524
    @subhamrajgarhia2524 4 місяці тому +1

    THIS IS MORE OPTIMAL APPROACH
    public class Solution {
    public ListNode detectCycle(ListNode head) {
    Map map = new HashMap();
    ListNode slow = head;
    ListNode fast = head;
    while(fast != null && fast.next != null) {
    slow = slow.next;
    fast = fast.next.next;
    if(slow == fast) {
    ListNode p1 = head;
    ListNode p2 = slow;
    while(p1 != p2) {
    p1 = p1.next;
    p2 = p2.next;
    }
    return p1;
    }
    }
    return null;
    }
    }

  • @crushed_oreos
    @crushed_oreos 2 роки тому +10

    Thanks for explaining the intuitions so clearly Striver, really makes coding up the solution a bit easier. ❤

  • @ritikatiwari3753
    @ritikatiwari3753 2 роки тому +2

    you are such an amazing person you have saved so many lives god bless you!!! lots and lots of love and power to you.

  • @wanderer_ankur
    @wanderer_ankur 4 роки тому +4

    This question's approach was very similar to the first question of SDE sheet. Thank you strive for helping so much :)

  • @rahulgovindkumar3105
    @rahulgovindkumar3105 3 роки тому +5

    That was an awesome intuition explanation .......... really really really thank you so much for your efforts

  • @prakashjha7238
    @prakashjha7238 3 місяці тому

    Thanks for the math behind the algorithm!
    I also wish to be guiding person to many.

  • @thelimit9719
    @thelimit9719 4 роки тому +16

    in interviews, apart from algos , do they ask qns like implement ds like a deque, circular linked list etc ?

  • @byomakeshpanda8055
    @byomakeshpanda8055 Рік тому +1

    That intuition part 🤩.
    Thanks Striver ❤❤

  • @gatishmehta2039
    @gatishmehta2039 2 роки тому +3

    This is exactly what I was looking for. Thank you so much! :)

  • @ranasauravsingh
    @ranasauravsingh 2 роки тому +1

    UNDERSTOOD... !!!
    Thanks striver for the video... :)

  • @amitpaunikar3408
    @amitpaunikar3408 4 роки тому +2

    Hi ... Good explanation of all topics
    Some linked list question is remaining
    Clone a list with next and random pointer
    Detect a cycle and remove loop from list
    Waiting for this topic video

    • @takeUforward
      @takeUforward  4 роки тому +6

      Everything will come :), with the help of this problem you can remove the loop also, just keep track of the previous pointer to slow when slow meets the entry pointer, so you can easily point the previous pointer to NULL, and you were successful in removing the loop :)

  • @satyamgupta6030
    @satyamgupta6030 Рік тому +1

    thanks alot striver ur explaination's are very good and easy to understand.

  • @tirthpatel20
    @tirthpatel20 Рік тому

    nice intuition #striver especially for the entry pointer and slow pointer point to find cycle start point.

  • @priyanshumahato5270
    @priyanshumahato5270 3 роки тому +3

    dude this explanation was the best soo far : )

  • @sayantaniguha8519
    @sayantaniguha8519 2 роки тому +1

    10:03
    Even if we write *entry=head* separately, it wont affect space complexity.
    Cuz, we are using 'entry' pointer to traverse a part of the list .
    We are not inserting nodes into it .
    Right ?

  • @gowdhamt1651
    @gowdhamt1651 2 роки тому

    Perfect explanation about the Intuition , Thank you!!

  • @jayachandra677
    @jayachandra677 4 роки тому +6

    I solved this today in the morning, I luckily assumed that the head pointer will always meet the slow pointer at some point. When I tried it for a couple of examples, I understood that my assumption was true and my code got accepted. Thank you for your thorough explanation bhaiya!

    • @takeUforward
      @takeUforward  4 роки тому +14

      Was the intuition clear?

    • @aysams2
      @aysams2 Рік тому +1

      @@takeUforward yes sir, it certainly was.

  • @NeerajSharma-mz4es
    @NeerajSharma-mz4es 3 роки тому

    Want to understand the concept in minimal time with all approaches this is the channel

  • @sudiptadas2806
    @sudiptadas2806 Рік тому

    You have explained the problem in a very easy way. thanks a lot

  • @shikharathaur6664
    @shikharathaur6664 3 роки тому +1

    Such a wonderful explanation of intuition. Thanks for the efforts !

  • @devangsingh2950
    @devangsingh2950 3 роки тому +3

    I have a doubt if we take a fast pointer travelling twice the distance than slow pointer, they are bound to meet and then we can find the starting node of the linked list by travelling from the meeting point. What if they move at random speeds fast = 3*slow, then also they are bound to meet(Using hash table probing logic) but then how can we find the start of the cycle then?

  • @hardikagarwal3938
    @hardikagarwal3938 3 роки тому +12

    L2 is the dist covered by slow pointer, which may include some cycles and the dist from entry point to point of intersection. So how the L1 = nC-L2 be certainly equal to the remaining dist of the cycle?

    • @anuragjana111
      @anuragjana111 2 роки тому

      Same question

    • @DTMAPunitSingh
      @DTMAPunitSingh Рік тому +1

      You can add n1C to slow pointer and you will get same result

    • @adityavishalsingh8624
      @adityavishalsingh8624 Рік тому

      12:55
      Doesn't matter if slow have covered Cycles or not .. let's assume it have some cycles (x turns) and for sure if slow have cycle so fast will cover cycle(y turns) more than the slow one... So to make things convenient you can make x to zero and corresponding update y to (y-x) .. hope it now make sense.

  • @rishabhrathore1727
    @rishabhrathore1727 Рік тому

    you make look these algorithms questions soo easy man
    i am in love with your content

  • @lightninghunterCR
    @lightninghunterCR Рік тому

    Understood!! And damn that intuition reminds me of Discrete Mathematics!

  • @binodbinod7537
    @binodbinod7537 4 роки тому +1

    Thank you soo much for the video ❤️🙏

  • @abhinilnath1900
    @abhinilnath1900 10 місяців тому

    BRILLIANT INTUTION

  • @priyaj9908
    @priyaj9908 2 роки тому

    Your explanation is very clear and understandable. Thank you so much😊

  • @stevewilsonraj
    @stevewilsonraj Рік тому

    thank you striver !!!

  • @AkhileshKumar-lv7yv
    @AkhileshKumar-lv7yv 3 місяці тому

    Thank you for the explanation!

  • @kaichang8186
    @kaichang8186 2 місяці тому

    understood, thanks for the great explanation

  • @rohithreddy8976
    @rohithreddy8976 2 роки тому

    This is the only video where I understood intuition. Thank you so much, Bro

  • @AKASH-sw9bs
    @AKASH-sw9bs 2 роки тому

    what a clean explanation .. i also watched the video from some of the other youtube tutorials but they represented the same thing in a much more complex way...
    Thanks brother for making the algorithm so simpler to understand .

  • @SATYAPRAKASH-ph1kk
    @SATYAPRAKASH-ph1kk 9 місяців тому

    very well explained in detail and also the code is very to understand and code

  • @prathamjain8937
    @prathamjain8937 10 місяців тому

    Since time complexity is O(n) means we are sure that slow pointer and fast will meet before the slow traverses all the elements .I mean how are we sure that slow will not loop more than once in cycle before meeting fast . Can someone please explain

  • @VaishnaviNigam
    @VaishnaviNigam 4 роки тому +1

    BESTTTTT EXPLAINATION🤩🤩🤩🤩🤩🤩

  • @rohangangwar6604
    @rohangangwar6604 3 роки тому

    bhaiya jitna mja algo me ni aaya usse kahi jada intution se aaya...thank u so much bhaiya

  • @sahilgoyals
    @sahilgoyals 4 роки тому

    Super Clear, Thank you so much sir 🤩

  • @tanushree0106
    @tanushree0106 8 місяців тому

    Thank you so much raj bhaiya..may god always bless you😇

  • @Hound77
    @Hound77 3 роки тому +1

    why are we checking for fast->next && fast->next->next is there any edge case which we will miss if we use fast->next && fast?

  • @arhitakundu5846
    @arhitakundu5846 Рік тому

    The best explanation on youtube!

  • @jackisname6825
    @jackisname6825 Рік тому

    i have a question striver if suppose slow and fast pointer will collide at node(8) then i guess slow and entry pointer will never point to the same node according to the operations applied on slow and entry pointer?? please answer this question

  • @meshkatuddinahammed
    @meshkatuddinahammed Рік тому

    Bro, when about the string playlist is coming? Eagerly waiting for it. Thanks!

  • @nagame859
    @nagame859 Рік тому

    One of the best explanations of yours! 🎩📴

  • @ragnarT3
    @ragnarT3 4 роки тому +1

    There is some kind of flute like sound coming... 2:45-2:50 here it is clearly noticeable. Great work bhai... Just thought of letting u knw about the noise 😀

    • @takeUforward
      @takeUforward  4 роки тому +1

      oh chair awaaz krta front back jb krta hun

  • @Yag116
    @Yag116 Рік тому

    cant we add a condition to optimize TC as at 6:48 slow already collides with fast pointer ?

  • @sumekagarwal8229
    @sumekagarwal8229 3 роки тому

    Which hash table to use in the naive approach? set or a map?
    and how to store it...........set?
    class Solution {
    public:
    ListNode *detectCycle(ListNode *head) {
    set s;
    ListNode * tmp = head;
    while(tmp!=NULL){
    if(s.find(tmp)!=s.end()){
    return tmp;
    }
    s.insert(tmp);
    tmp=tmp->next;
    }
    return NULL;
    }
    };
    please correct this.🤶

  • @uptonogood300
    @uptonogood300 4 роки тому +3

    was able to solve it with little different approach even before seeing the solution . thanks to the previous videos in the playlist !

  • @ritikashishodia675
    @ritikashishodia675 2 роки тому +1

    Bhaiya hashing mind m ai O(1) nahi Hua usme ek problem ai us cycle s jo extra node h uski vjh s . Agr slow or fast us cycle k start pr khade ho to same honge kuch us loop m travel krne k bd

    • @ritikashishodia675
      @ritikashishodia675 2 роки тому

      Thank u bhaiya bs ek point nahi such payi last vala ki Jo gap arra h start or phuchne m cycle k vo entry s pura ho skta h 🤩🤩🤩 thanks a lot bhaiya....

  • @kewaltakhellambam7710
    @kewaltakhellambam7710 Рік тому

    such an intricate solution! Nice

  • @sourabhkumar6194
    @sourabhkumar6194 3 роки тому

    That verification part explained very well

  • @shivamgupta336
    @shivamgupta336 3 роки тому

    I think you have not considered one condition if fast and slow pointer meets at starting point. In this case entry and slow are giving wrong answer .

  • @shafeymalik5334
    @shafeymalik5334 Рік тому

    can anyone answer is it possible if the entry and slow keeps revolving anf they never meet?

  • @bhaveshsoni6684
    @bhaveshsoni6684 3 роки тому +1

    I used one approach to solve the same problem with exactly o(n) complexity. In this approach, I changed the value of every node with my name. if I find my name again, then it is the Cycle starting point. Is it the right approach?

    • @takeUforward
      @takeUforward  3 роки тому +1

      Yes it is, but modifying given data is not allowed generally if it can be done without it.

  • @kamalnayan5331
    @kamalnayan5331 4 роки тому

    Thanks for the video .🌞

  • @astrid_6622
    @astrid_6622 Рік тому

    how do we know that nc-L2 is the distance needed to be travelled by slow pointer ? i am assuming the fast pointer only takes on turn more to reach upto slow pointer

  • @Steve_Chandan
    @Steve_Chandan 4 роки тому

    really i like your explanation all the time.😊😊😊

  • @-ShangsitNath
    @-ShangsitNath 2 роки тому +1

    why distance travelled by fast pointer is twice the distance travelled by slow pointer?? Is it bcoz, fast pointer is taking 2 steps at a time?

    • @crushed_oreos
      @crushed_oreos 2 роки тому

      yes, so if we do n iterations, fast pointer covers 2*n steps and slow pointer covers 1*n steps

  • @shivamchauhan029nitjsr4
    @shivamchauhan029nitjsr4 Рік тому

    bhaiya agar input mein non-cyclic linkedList ajati h (in case) to while loop SEGGS dega i guess.

  • @ShubhP-t2c
    @ShubhP-t2c Рік тому

    5:23

  • @dreamyme543
    @dreamyme543 2 роки тому

    Great explanation , Thank you:)

  • @be_like__prateek
    @be_like__prateek 4 роки тому +1

    @take U forward Bhai how many iterations will fast pointer loop within the loop in the worst case ?
    Is the answer 2 ??

    • @accepted5856
      @accepted5856 3 роки тому

      same doubt

    • @yatinarora1252
      @yatinarora1252 3 роки тому

      Yes it is taking twice the number of iterations so it will take 2 iterations kind of and regarding it may happen in wrost case they won't find any cyclr

  • @madanmohan5661
    @madanmohan5661 2 роки тому

    Can someone tell me after detecting the loop how we can remove it from the list?

  • @krishanusaha5212
    @krishanusaha5212 Рік тому

    Great Explanation 🔥

  • @gauravtripathi9456
    @gauravtripathi9456 3 роки тому +1

    Wow, such a good explanation of the intuition behind the algorithm. Thanks for the effort !

  • @gayathrijaini2386
    @gayathrijaini2386 3 роки тому +1

    Is it nC-l2 or C-l2. Bcoz one cycle length is c right? 🤔

  • @mukuljain4087
    @mukuljain4087 Рік тому

    but why are you not considering the cycle of slow pointer

  • @amritraj658
    @amritraj658 4 роки тому +1

    Bhaiya mai core branch se hu 1st year...kya mai IT Related company me ja sakta hu as a SDE, mai start kar diya programming sikhna ...... plz reply 🙏

  • @gnaneshwarkandukuri6733
    @gnaneshwarkandukuri6733 2 роки тому

    how fast pointer dist=2* slow pointer....?

  • @PriyanshuKumar-bx9oy
    @PriyanshuKumar-bx9oy Рік тому

    Can anybody elaborate how L1 becomes equal to nc-L2 in general not from equation?

  • @anilyadav-ky1bg
    @anilyadav-ky1bg 3 роки тому

    Hi Bhayia, in outer loop while i was like

  • @shyamjeegupta6173
    @shyamjeegupta6173 2 роки тому

    would not the TC of first approach be O(NlogN), logN for searching the given address is present in hash table or not ??
    Thanks

    • @crushed_oreos
      @crushed_oreos 2 роки тому

      in c++ time complexity for searching an element in unordered set is O(1)

  • @rudrasimhaa269
    @rudrasimhaa269 3 роки тому

    Anybody know who is the Genius that first come up with this idea?

  • @shivanandprasad2827
    @shivanandprasad2827 3 роки тому

    ListNode *detectCycle(ListNode *head) {
    ListNode*fast = head;
    ListNode*slow = head;

    bool cycle = false;
    while(fast != NULL && fast->next != NULL){
    slow = slow->next;
    fast = fast->next->next;
    if(slow == fast){
    cycle = true;
    break;
    }
    }

    if(!cycle)
    return NULL;

    ListNode*temp = head;
    while(temp != slow){
    slow = slow->next;
    temp = temp->next;
    }
    return slow;
    }
    };

  • @welcometoc.s.easpirants
    @welcometoc.s.easpirants 7 місяців тому

    You Rock Man.

  • @dhanashreegodase4445
    @dhanashreegodase4445 3 роки тому

    Thanks for the effort

  • @gourabsinha
    @gourabsinha 4 роки тому

    Why not we are making the fast pointer jumps three nodes?

    • @takeUforward
      @takeUforward  4 роки тому

      it been stated in the previous video... already said that in the video

    • @gourabsinha
      @gourabsinha 4 роки тому

      @@takeUforward but it's for only fast pointer jumping two times that doesn't clear my doubt. Let's say a vehicle A is having v speed and other vehicle B which is having 3v speed and distance between them is D where A is in front of B. Then also B will catch A after some time for sure as speed of B > A. Then why aren't we considering that one. It will be faster know?

    • @takeUforward
      @takeUforward  4 роки тому +2

      No the chances of colliding sooner is with fast jumping twice :)

    • @thelimit9719
      @thelimit9719 4 роки тому

      @@gourabsinha correct me if im wrong . i think its not guarenteed with 3 jumps they collide. for eg: t=0, posA=3, posB=0, speedA=1, speedB=3
      t=1, posA=4, posB=3
      t=2, posA=5,posB=6
      now impossible to collide.
      but u take any example of ur choice and use fast as 2jumps ahead, they r bound to collide

  • @shashankgsharma0901
    @shashankgsharma0901 5 місяців тому

    Understood!

  • @bhavyagarg9763
    @bhavyagarg9763 2 роки тому

    The explanations are very precisely explained and hence easy to understand . Thanks a lot for the amazing content. Keep up the good work.

  • @auroshisray9140
    @auroshisray9140 3 роки тому

    Great explanation as always.

  • @tanishkumar5827
    @tanishkumar5827 Рік тому

    well explained !

  • @jaihari1404
    @jaihari1404 2 роки тому

    hey hey hey good explanation,but i hava an problem where can i learn this type of "maths":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::>>>>>>>>>>>>>>>>>>>

  • @practice8844
    @practice8844 3 роки тому

    Best teacher ever

  • @vickyarora7380
    @vickyarora7380 3 роки тому

    Very helpful!

  • @gigachadkartik
    @gigachadkartik 2 роки тому

    mazedaar, nice video

  • @AbhishekKumar-td5zu
    @AbhishekKumar-td5zu 4 роки тому

    Tqsm bhaiya ♥️♥️

  • @jeetintyagi
    @jeetintyagi 4 роки тому

    ListNode *detectCycle(ListNode *head) {
    if( head == NULL || head->next ==NULL )
    return NULL;


    ListNode* slow = head;
    ListNode* fast = head;

    while(fast->next && fast->next->next){
    fast = fast->next->next;
    slow = slow->next;

    if(fast == slow){
    slow=head;
    //REUSING SLOW POINTER;
    while(fast !=slow){
    slow = slow->next;
    fast = fast->next;
    }
    return fast;
    }
    }
    return NULL;
    }

  • @subhadeepsadhukhan2875
    @subhadeepsadhukhan2875 Рік тому

    Thank you

  • @deepanshujindal9985
    @deepanshujindal9985 4 роки тому

    I m in 11 th tried c++ in lockdown and i like it and gonna make my courier in cs but i cant give jee or crack big iit but really wanna succesful in the field plz help

  • @vartikasinghania9723
    @vartikasinghania9723 3 роки тому +1

    Thank you so much bhaiya for such amazing explanations
    Can you please explain this
    Why 2(L1 + L2) = (L1 + L2 + nC)

    • @dineshchintu9779
      @dineshchintu9779 3 роки тому

      Let s be the speed of slow pointer and f be the speed of speed pointer
      and we know that f = 2 * s
      Let d1 be the distance covered by slow one and d2 be the distance covered by speed pointer
      and we know that (distance = speed / time)
      so, d1/d2=s/f
      d1/d2=s/2*s
      d1/d2=2
      so, d2 = 2 * d1

    • @shinei9459
      @shinei9459 3 роки тому

      @@dineshchintu9779 ur ryt about everything just change the distance formula since, distance=speed*time :-)

  • @sadabhalim5806
    @sadabhalim5806 4 роки тому

    Love you brother :)

  • @dontony7071
    @dontony7071 4 роки тому +1

    I have never encountered any linked list q in any cp platform. Is linked list interview specific?

    • @takeUforward
      @takeUforward  4 роки тому

      Mostly ! The STL you use can also be implemented using LinkedList. Since we use so much of STL, we don't care about the implementation. Hence these things are asked at Interviews!

  • @binodbinod7537
    @binodbinod7537 4 роки тому

    Hi bhaiyaa ❤️