-
-
Notifications
You must be signed in to change notification settings - Fork 5.7k
Added CycleNode Algorithm #754
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
f267d59
f4bfb61
4663496
d9658af
8ddab93
508b663
2e23432
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
/* | ||
Problem: Given a linked list, return the node where cycle begins. If there is no cycle return null | ||
|
||
Approach used: Floyd Cycle Detection Algorithm | ||
|
||
What is Floyd Cycle Detection Algorithm? | ||
- Floyd Cyclce Detection algorithm uses two pointer (slow & fast), in which fast pointer move twice the speed of slow pointer. | ||
- It is also known as hare and tortoise algorithm as we can imagine slow pointer as tortoise that moves slow and hare as the fast one. | ||
- If the fast pointer reaches null, that means there was no cycle. | ||
- If the fast pointer and slow pointer becomes equal that means there was cycle. | ||
|
||
For reference: https://www.codingninjas.com/blog/2020/09/09/floyds-cycle-detection-algorithm/ | ||
*/ | ||
|
||
/* | ||
Input: Pass the head (first node) of linked list | ||
*/ | ||
const detectCycleNode = (head) => { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add a specification for head. What type of input do you expect? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. That is not what I meant. I mean what properties and function do you expect the |
||
if (!head || !head.next) { | ||
return null | ||
} | ||
|
||
let slow = head | ||
let fast = head | ||
|
||
while (fast && fast.next) { | ||
slow = slow.next | ||
fast = fast.next.next | ||
if (slow === fast) break | ||
} | ||
|
||
slow = head | ||
|
||
while (fast && slow !== fast) { | ||
slow = slow.next | ||
fast = fast.next | ||
} | ||
|
||
return fast | ||
} | ||
|
||
export { detectCycleNode } |