Linked List Cycle:
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
.
Input: head = [3,2,0,-5], pos = 1
Output: true
Explanation: There is a cycle in the linked list,
where the tail connects to the 1st node (0-indexed).
Input: head = [3,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list,
where the tail connects to the 0th node.
Input: head = [3], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
[0, 10^4]
.-10^5 <= Node.val <= 10^5
pos
is -1
or a valid index in the linked-list.Try this Problem on your own or check similar problems:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head, fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast) return true;
}
return false;
}
}
We could store iterate over list and store nodes in hashset and if encounter same node again we would know there is a cycle in the linked list. That would bring the space complexity to O(n)
. Can we improve this? Well, we can always remember the famous movie scene “On your left” from Captain America and think of the two pointers as runners (captain being the fast-er one). If their running track is a cycle there is a point when the fast runner will enter the cycle,
and there is a point when the slow runner will enter the cycle, but eventually they both will be in the cycle (if there is one). At some point while in the cycle the fast pointer will do the “on your left” to the slow pointer (in other words they will meet), so we just must check if the pointers are pointing to the same node while iterating over list. If they are, we return true
since there is a cycle in the list.
Don’t settle for anything less than the crown. Join our newsletter and become the King of Interviews! Click here to join now and get the latest updates.