The 30 second answer
I send a slow pointer one step at a time and a fast pointer two steps. If there is a cycle they will meet; if the fast pointer reaches null there is no cycle. The algorithm uses constant extra memory and does not change the list.
Problem Given the head of a linked list, return true if the list contains a cycle, otherwise false. A cycle means some node's next pointer points back to a previous node. Original: LeetCode 141: Linked List Cycle. HackerRank Linked Lists: Detect a Cycle is the same problem.
Understanding the prompt You may not assume you can mark nodes or use O(n) memory, although a set of seen references is a correct first answer. The official problem allows a cycle that starts at any index, including the head.
Pattern recognition Fast and slow pointers, also called Floyd cycle detection: two pointers moving at different speeds on a loop will meet.
Brute force Put every node in a HashSet as you walk. A repeated reference is a cycle. That is O(n) time and O(n) space.
Optimal slow and fast both start at head. While fast and fast.next are non-null, advance slow by one and fast by two. If they ever refer to the same node, there is a cycle. If fast falls off the end, there is not.
Alternatives Linked List Cycle II uses the same first phase, then a second pointer from the head to find the cycle start. HackerRank Detect a Cycle is this boolean version.
Java solution
public class LinkedListCycle {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
static ListNode list(int... a) {
var dummy = new ListNode(0);
var t = dummy;
for (int x : a) {
t.next = new ListNode(x);
t = t.next;
}
return dummy.next;
}
static String str(ListNode h) {
var sb = new StringBuilder("[");
for (ListNode p = h; p != null; p = p.next) {
if (sb.length() > 1) sb.append(", ");
sb.append(p.val);
}
return sb.append("]").toString();
}
static 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;
}
public static void main(String[] args) {
var a = list(3, 2, 0, -4);
a.next.next.next.next = a.next; // tail links to index 1
System.out.println(hasCycle(a)); // true
var b = list(1, 2);
b.next.next = b;
System.out.println(hasCycle(b)); // true
System.out.println(hasCycle(list(1))); // false
}
}Complexity O(n) time, O(1) extra space.
Edge cases
- Official-style samples: 3 -> 2 -> 0 -> -4, with the tail linked to 2, returns true; 1 -> 2 linked back to 1 returns true; a single node with no cycle returns false.
- A cycle that includes the head.
- An empty list returns false.
Follow-ups
- Return the node where the cycle begins: Linked List Cycle II.
- Find the cycle length: after the meeting point, walk slow until it returns, counting steps.
Tests A list 3,2,0,-4 with the tail linked to 2 returns true. A two-node cycle returns true. A single node with no cycle returns false.
How to say it in the interview "I use a slow pointer that moves one step and a fast pointer that moves two. If they meet, there is a cycle; if fast reaches null, there is not. Constant extra space, no need to mark nodes."
Sources (2)
- LeetCode 141: Linked List Cycleleetcode.com
- HackerRank: Linked Lists: Detect a Cyclehackerrank.com