19. Linked List Cycle
easyAsked at OlaDetect whether a linked list contains a cycle.
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
Number of nodes is in [0, 10^4]-10^5 <= Node.val <= 10^5
Examples
Example 1
head = [3,2,0,-4], pos = 1trueExample 2
head = [1], pos = -1falseApproaches
1. Visited set
Walk and record nodes; if we revisit one, there is 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
Two pointers; slow moves one, fast moves two. They meet if there is a cycle.
- 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:
Ola-specific tips
Ola interviewers ask the constant-space version to gauge pointer fluency; tie it to detecting circular dependency in dispatcher retry chains.
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 Ola interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →