11. Linked List Cycle
easyAsked at MercuryDetect whether a 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. A cycle exists when a node's next pointer points back to a previously visited node, forming a loop.
Constraints
Node count 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
Walk the list and store node references in a Set.
- 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 advances one step, fast two; if there's a cycle they collide. Constant space and linear time.
- 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:
Mercury-specific tips
Mercury reuses this to test cycle detection in transfer chains — circular money movements between subsidiaries trigger KYC flags, so cycle-detect logic must run before posting any wire.
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 Mercury interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →