Linked List Cycle II

 Algorithms and approach and Intuitions 

approach 1:

1.find the collision pts (slow and fast)

2.find the entry pts of cycle 

 slow = l1+ l2;

fast = l1+l2+nc; where n  is the no of cycle in linkedlist

fast = 2slow

l1 = nc - l2;

approach 2:

same as linkedList cycle I

Code 

 // //time complexity ~ O(N) and space complexity is O(1);
    ListNode *detectCycle(ListNode *head) {
        if(head==NULL || head->next==NULL){
            return NULL;
        }
        ListNode* slow = head;
        ListNode* fast = head;
        ListNode* entry = head;
        while(fast->next!=NULL && fast->next->next!=NULL){
            //find the collision point of fast and slow
            slow = slow->next;
            fast = fast->next->next;
            if(slow == fast){
                //find the entry point of cycle 
                while(entry!=slow){
                    entry = entry->next;
                    slow = slow->next;
                }
                return entry ;
            }
        }
        return NULL;
    }
    
    // approach 2nd time complexity = O(N)  //tranverse
    // space complexity = O(N); // hashtable 
    // ListNode *detectCycle(ListNode *head) {
    //     ListNode* dummy = head;
    //     std::unordered_set<ListNode*> s;
    //     while(dummy!=NULL){
    //         auto val = s.find(dummy);
    //         if(val!=s.end()){
    //             return *val;
    //         }
    //         dummy = dummy->next;
    //     }
    //     return NULL;
    // }

Comments

Post a Comment

Popular posts from this blog

Linked List Cycle (Leetcode)

Palindrome Linked List (LeetCode)