Skip to main content

19. Linked List Cycle

easyAsked at Lyft

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, determine if the list has a cycle in it. There is a cycle if some node can be reached again by continuously following the next pointer.

Constraints

  • Number of nodes in range [0, 10^4]
  • -10^5 <= node value <= 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. Hash set visited

Track visited nodes in a Set; revisit means cycle.

Time
O(n)
Space
O(n)
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 — slow moves 1 step, fast 2. If they meet, there's a 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:

Lyft-specific tips

Lyft loves the tortoise-hare pattern — they'll mention they use it to detect loops in driver-route stack frames and want you to explain why it always terminates.

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

Practice these live with InterviewChamp.AI →