19. Linked List Cycle
easyAsked at BoxDetect a cycle in a singly linked list — Box uses this idea to spot cyclic symlink references in folder graphs before they crash the indexer.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle if some node can be reached again by continuously following the next pointer.
Constraints
0 <= number of nodes <= 10^4-10^5 <= Node.val <= 10^5
Examples
Example 1
head = [3,2,0,-4], pos = 1trueExample 2
head = [1,2], pos = -1falseApproaches
1. Hash set of visited nodes
Walk the list, store each node; return true on a repeat.
- Time
- O(n)
- Space
- O(n)
const seen = new Set();
let c = head;
while (c) {
if (seen.has(c)) return true;
seen.add(c);
c = c.next;
}
return false;Tradeoff:
2. Floyd's tortoise and hare
Slow and fast pointers; if they meet there is a cycle. O(1) space.
- Time
- O(n)
- Space
- O(1)
function hasCycle(head) {
let slow = head, fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}Tradeoff:
Box-specific tips
Box wants the Floyd's cycle pointer pair — they map it to detecting cyclic symlink chains in folder-graph traversal without burning memory on visited-sets.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Linked List Cycle and other Box interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →