Skip to main content

11. Linked List Cycle

easyAsked at Ramp

Detect 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 there is a cycle in the linked list. There is a cycle if there is some node that can be reached again by continuously following the next pointer.

Constraints

  • The number of nodes is in the 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. Brute force with set

Track visited node references in a Set.

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

Two pointers advance at different speeds; they meet inside a cycle, otherwise the fast pointer hits null.

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:

Ramp-specific tips

Ramp uses cycle detection inside their approval-graph engine — a manager who delegates back to a subordinate creates a routing cycle, and two-pointer detection is the canonical way to flag it cheaply.

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

Practice these live with InterviewChamp.AI →