9. Linked List Cycle
easyAsked at SquarespaceDetect whether a singly linked list contains a cycle; Squarespace uses it to gauge whether you know Floyd's two-pointer technique versus building a visited set.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the head of a linked list, determine if the list has a cycle in it. A cycle exists 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=1 (tail connects to index 1)trueExample 2
head=[1,2], pos=-1falseApproaches
1. Visited set
Walk the list and bail out as soon as a node repeats.
- 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, one stepping by one and one by two, must collide inside a cycle. Constant extra memory.
- 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:
Squarespace-specific tips
Squarespace reviewers like the link to their template-block dependency graph, where cycle detection guards against infinite include loops at publish time.
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 Squarespace interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →