0

Check if Singly Linked list has a cycle

Problem:

Checking if linked has a cycle . This means that there will be no ‘null’ value for address pointer in linked list.

Logic:

I.  Without extra space solution:

If  linked list has a cycle then there never going to be a null node. So it is important to decide exit condition from loop carefully.

We will assign two nodes, one to head and one to head next. If there is cycle, then there will be a point where both temporary nodes will be pointing to same node and if there is no cycle then one of them(tempNode2 because it is assigned to next to tempNode1 at start) will become null.

Time complexity for this solution is O(n)

When cycle is present in linked list then tempNode1 traverse at the max n nodes and tempNode2 will traverse through linked list faster than tempNode1 and will examine n nodes.  If cycle not present in Linked list then tempNode2 will become null after traversing n nodes. So time complexity of this solution is O(n).

II.Using extra list:

In this solution we will create a list and will add each node to the list if its not already present in that list. We will continue adding node till tempNode is not null.

This solution uses extra space so not feasible for long linked list.

Each new node will be compared with all its previous nodes. So for ‘n’ node there will be ‘n-1’ comparisons. So time complexity of this solution is O(n).

Space complexity of this solution is O(n).