Skip to main content

11. Linked List Cycle

easyAsked at Monzo

Detect whether a chain of transactions forms a loop, which would corrupt the ledger.

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

Problem

Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle if some 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,2], pos = -1
Output
false

Approaches

1. Hash set of visited nodes

Walk the list and store each node reference; report a cycle the first time we revisit one.

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 two-pointer

Move slow one step and fast two steps; they meet if and only if a cycle exists. 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:

Monzo-specific tips

Monzo cares about constant-space invariants when sweeping transaction chains during faster-payments reconciliation.

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

Practice these live with InterviewChamp.AI →