Skip to content
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

Floyd’s Cycle Detection Algorithm #16

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

Anshuman7080
Copy link

Use of Floyd's Cycle Detection:

The detectLoop function now uses two pointers (slow and fast). The slow pointer moves one step at a time, while the fast pointer moves two steps. If there is a loop, the two pointers will eventually meet.
Constant Space Complexity:

This algorithm uses no extra space, thus achieving
𝑂
(
1
)
O(1) space complexity compared to the
𝑂
(
𝑛
)
O(n) space used in the previous approach with a hash set.
Early Exit:

The function checks if the head is nullptr right away, allowing for an early exit if the list is empty.
This implementation is not only efficient but also straightforward and easy to understand, making it a great choice for detecting loops in linked lists.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant