19. Linked List Cycle
easyAsked at SlackDetermine whether a singly linked list contains a cycle.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the head of a linked list, determine if the list has a cycle. A cycle exists if some node can be reached again by continuously following the next pointer.
Constraints
Number of nodes in [0, 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. Visited set
Track nodes seen in a Set; a revisit means a cycle.
- Time
- O(n)
- Space
- O(n)
const seen=new Set();
let n=head;
while(n){ if(seen.has(n)) return true; seen.add(n); n=n.next; }
return false;Tradeoff:
2. Floyd's tortoise and hare
Move slow by 1 and fast by 2. If they meet, there is a cycle. Constant 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:
Slack-specific tips
Slack relevant context — pubsub channel-listener chains can cycle; interviewers grade whether you mention loop-detection in async dispatchers.
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 Slack interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →