Skip to main content

13. Linked List Cycle

easyAsked at Figma

Detect whether a singly linked list contains a cycle. Figma uses this to gauge whether you reach for the two-pointer trick or burn memory on 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. Return true if any 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

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

Example 2

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

Approaches

1. Visited set

Walk the list and store seen nodes in a Set; return true on collision.

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

Tradeoff:

2. Floyd's tortoise and hare

Run slow and fast pointers; if the fast pointer ever meets the slow pointer inside the list, there is a cycle. Otherwise fast hits null and we know the list terminates.

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:

Figma-specific tips

Figma's hidden grade is whether you can explain WHY two-pointer works — talk about the relative speed of 1-step versus 2-step pointers closing any gap inside a cycle.

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 Figma interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →