Problem of the day
You are given a Singly Linked List of integers. Return true if it has a cycle, else return false.
A cycle occurs when a node's next points back to a previous node in the list.
In the given linked list, there is a cycle, hence we return true.
The first line of each test case contains the elements of the singly linked list separated by a single space and terminated by -1. Hence -1 would never be a list element.
The second line contains the integer position 'pos', representing the position (0-indexed) in the linked list where the tail connects. If 'pos' is -1, there is no cycle in the linked list.
The only output line contains 'true' if the linked list has a cycle or 'false' otherwise.
You don't have to print by yourself explicitly. It has been taken care of.
1 2 3 4 -1
1
true
The linked list given in the input is as follows:
1 2 3 4 -1
0
true
The linked list given in the input is as follows:
5 -1
-1
false
The linked list given in the input is as follows:
Try to solve this problem in O(n).
Try to solve this problem in O(1).
0 <= n <= 10^6
-1 <= pos < n
-10^9 <= data <= 10^9 and data != -1
Where 'n' is the size of the singly linked list, 'pos' represents the position (0-indexed) in the linked list where the tail connects to, and 'data' is the Integer data of the singly linked list.
Time Limit: 1 sec
Think of checking each node as the starting point for the cycle.
We are going to have two loops outer-loop and inner-loop
O(N*N), where N is the total number of nodes.
For every iteration of outer-loop, we are iterating the linked-list again.
O(1).
Constant space is used.