Skip to main content

9. Linked List Cycle

easyAsked at Wise

Detect whether a singly linked list contains a cycle — a cheap probe of pointer hygiene, exactly the discipline Wise needs in their settlement engine.

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

Problem

Given the head of a linked list, determine if it contains a cycle. Return true if there is a cycle, otherwise false. Solve with O(1) extra space.

Constraints

  • 0 <= nodes <= 10^4
  • -10^5 <= Node.val <= 10^5
  • O(1) space required for full credit

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, store each node reference in a Set, return true on a repeat.

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

Tradeoff:

2. Floyd tortoise and hare

Two pointers move at speeds 1 and 2; if a cycle exists they collide, otherwise the fast pointer hits null. Constant 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:

Wise-specific tips

Wise rewards the O(1)-space answer here because their settlement workers reuse pointer-walking patterns to detect routing loops that would otherwise spin a payment forever.

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

Practice these live with InterviewChamp.AI →