Detect Loop in Linked List

How to detect loop in linked list.

Given a linked list, determine if it has a cycle or loop in it.

For example:

In the below example, the last node (whose value is 9) points to node whose value is 5. The last node of a linked list does not points to a null. It has a cycle.

Detect a loop in a linked list

Detect loop in a linked list

In this tutorial, I am going to discuss multiple approaches with their time and spaces complexities to solve this problem.

Programming video tutorials

Linked list video tutorials

Find Loop in Linked List using Set

How to detect cycle in a linked list?

The easiest way is to check whether the node is already visited or not. For this we need additional data structure to store the node reference.

Here are the steps to detect cycle in a linked list using set. We are using set because it does not allow duplicates. Also, the lookup time is O(1).

i) Visit each node one by one and store the node reference in a HashSet.
ii) If null is reached at any point then return false. It means linked list does not have a loop or cycle in it.
iii) If node reference is found in a HashSet then return true. It means linked list has a loop or cycle in it.

The time complexity of this approach is O(n) and it’s space complexity is also O(n).

Find Middle Element of a Linked List

Detect Loop in a Linked List (Floyd’s Cycle-Finding Algorithm) – Java Code

In our previous approach, we have used additional data structure to detect loop in a linked list.

In this example, I am going to discuss how we can solve this problem using two pointers without using additional space.

To solve this problem we can use two pointers slow and fast. The idea here is to traverse a linked list using two pointers. The slow pointer move by one step and the fast pointer move by two step. If slow and fast pointers meet at some point then there is a loop in a linked list. If the pointer reaches at end (points to a null) then the linked list does not have a cycle.

The time complexity of this approach is O(n) and it’s space complexity is O(1).

Programming questions on linked list

Detect Loop in Linked List Video Tutorial

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.