Created
October 21, 2017 19:40
-
-
Save shailrshah/e542c8ab0f16f918b09d4f2d6165cc5f to your computer and use it in GitHub Desktop.
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Floyd's cycle-finding algorithm | |
public ListNode detectCycle(ListNode head) { | |
if(head == null) | |
return null; | |
ListNode fast = head; | |
ListNode slow = head; | |
while(fast.next != null && fast.next.next != null) { | |
fast = fast.next.next; | |
slow = slow.next; | |
if(fast == slow) { | |
// Linked List has a loop | |
// Let distance from head to start of loop be A | |
// Let distance of the loop be B + C | |
// Let slow pointer travel A + B | |
// Since fast pointer is twice as fast, it travels A + B + C + B, or 2(A + B) | |
// 2(A + B) = A + 2B + C => A = C | |
// So, let the slow node complete the loop (C steps) | |
// In the mean time, bring fast node to head and move it at the same speed as slow's | |
// Both nodes will intersect at the starting point | |
fast = head; | |
while(slow != fast) { | |
slow = slow.next; | |
fast = fast.next; | |
} | |
return slow; | |
} | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment