Skip to main content

6. Linked List Cycle

easyAsked at Rappi

Detect whether a linked list contains a cycle — Rappi frames this as catching a circular hand-off in a courier-to-courier relay before it deadlocks dispatch.

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

Problem

Given the head of a linked list, determine if the list has a cycle. A cycle exists if a node can be reached again by continuously following the next pointer.

Constraints

  • 0 <= nodes <= 10^4
  • Use O(1) extra memory if possible

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

Track every node visited; if you revisit, there is a cycle.

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

Tradeoff:

2. Floyd's tortoise and hare

Advance two pointers at different speeds; if they meet, the list has a cycle — constant 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:

Rappi-specific tips

Rappi expects the Floyd cycle-detection approach because their dispatch graph traversal must run in constant memory under high courier-fanout load.

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

Practice these live with InterviewChamp.AI →