141. Linked List Cycle
Asked at 23Microsoft55Amazon53Bloomberg53Google47Meta43Infosys58Nvidia55Yahoo97Qualcomm68Nagarro67Huawei67Intel66SAP62Autodesk59Palo Alto Networks59Cisco56Cognizant48IBM44tcs42DE Shaw38Oracle35Goldman Sachs33Yandex28
Problem
Decide whether a linked list contains a cycle, i.e. following next pointers eventually revisits a node.
Example: 3→2→0→-4 with the tail pointing back to the node 2 → true
Constraints: follow-up: O(1) extra memory.
Floyd: slow moves 1, fast moves 2. If there's a cycle they must meet; otherwise fast hits null.
Complexity: O(n) time, O(1) space.
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow is fast:
return True
return False
h = make_list([3, 2, 0, -4]); h.next.next.next.next = h.next # tail -> node 1
assert Solution().hasCycle(h) is True
assert Solution().hasCycle(make_list([1])) is False
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;
}
}
func hasCycle(head *ListNode) bool {
slow, fast := head, head
for fast != nil && fast.Next != nil {
slow, fast = slow.Next, fast.Next.Next
if slow == fast {
return true
}
}
return false
}