Description
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
Example 1:
1Input: head = [3,2,0,-4], pos = 1
2Output: true
3Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Example 2:
1Input: head = [1,2], pos = 0
2Output: true
3Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
Example 3:
1Input: head = [1], pos = -1
2Output: false
3Explanation: There is no cycle in the linked list.
Constraints:
- The number of the nodes in the list is in the range
[0, 10^4]. -10^5 <= Node.val <= 10^5posis-1or a valid index in the linked-list.
Follow up: Can you solve it using O(1) (i.e. constant) memory?
Solution
Using Hashing
One way to solve this problem is to use HashSet or HashMap to track which elements have already been visited. If we visit the same node twice, we can verify that from HashSet or HashMap api. This approach requires additional space in the form of HashMap or HashSet.
1class Solution {
2 public boolean hasCycle (ListNode head) {
3 Set<ListNode> set = new HashSet<>();
4 while (head != null) {
5 if (set.contains(head)) {
6 return true;
7 } else {
8 set.add(head);
9 }
10 head = head.next;
11 }
12 return false;
13 }
14}
- Time Complexity:
O(n) - Space Complexity:
O(n)
Using Fast and Slow Pointers
This problem can be solved using slow and fast pointers. If there is cycle in the linked list, the traversal should never end. It should traverse in the loop indefinitely. Thus if we use the slow pointer and fast pointers moving at two different speeds, the fast pointer will never reach the end of the list. Also, there will be at least one node in the list where slow pointer and fast pointers will meet during their traversal due to cycle. This means we can check if fast == slow and if that’s the case, we know that the list has a cycle else eventually the fast pointer will reach null (i.e. end of the list) and at that point, we can return false.
1class Solution {
2 public boolean hasCycle (ListNode head) {
3 ListNode slow = head;
4 ListNode fast = head;
5 while (fast != null && fast.next != null) {
6 slow = slow.next;
7 fast = fast.next.next;
8 if (slow == fast)
9 return true;
10 }
11 return false;
12 }
13}
- Time Complexity:
O(n) - Space Complexity:
O(1)


Comments