Skip to main content

15. Linked List Cycle

easyAsked at Activision

Detect whether a linked list contains a cycle — Activision uses this to gauge two-pointer instincts before chat-moderation graph cycle questions.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given the head of a linked list, return true if there is a cycle, otherwise false. A cycle exists if any node can be reached again by continuously following the next pointer.

Constraints

  • Node count in range [0, 10^4]
  • -10^5 <= Node.val <= 10^5

Examples

Example 1

Input
head=[3,2,0,-4], pos=1
Output
true

Example 2

Input
head=[1,2], pos=-1
Output
false

Approaches

1. Hash set seen

Walk and remember visited nodes; if you revisit, cycle.

Time
O(n)
Space
O(n)
const seen = new Set();
let cur = head;
while (cur) {
  if (seen.has(cur)) return true;
  seen.add(cur);
  cur = cur.next;
}
return false;

Tradeoff:

2. Floyd's tortoise and hare

Two pointers, fast moves twice as quickly. If they ever meet, cycle exists; if fast hits null, no cycle. O(1) 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:

Activision-specific tips

Activision watches whether you reach for Floyd's trick under O(1) space constraints — the same pattern shows up when scanning chat-moderation reply graphs for spam loops.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Linked List Cycle and other Activision interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →