Skip to main content

11. Linked List Cycle

easyAsked at Grab

Detect whether a linked list has a cycle — Grab uses this as a two-pointer fluency check.

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. Return true if there is a cycle, false otherwise.

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,2], pos = -1
Output
false

Approaches

1. Visited set

Walk the list and track each node in a Set.

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 tortoise and hare

Two pointers move at different speeds; if a cycle exists they meet, else fast reaches 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:

Grab-specific tips

Grab interviewers expect O(1) space — frame the cycle as a stale ride-event reference loop in their dispatch graph.

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

Practice these live with InterviewChamp.AI →