13. Linked List Cycle
easyAsked at MercadoLibreDetect whether a singly linked list contains a cycle.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the head of a linked list, return true if the list contains a cycle, otherwise false. A cycle exists when some node can be reached again by continuously following next pointers.
Constraints
0 <= node count <= 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
Walk the list, marking each node in a set; return true on revisit.
- 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 & hare
Two pointers, one moving one step and one moving two. If they meet, there's 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:
MercadoLibre-specific tips
MercadoLibre logistics teams use cycle detection on routing graphs — courier handoff sequences must not loop, and they want to see the constant-space pointer pattern, not a visited-set crutch.
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 MercadoLibre interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →