Skip to main content

7. Linked List Cycle

easyAsked at ByteDance

Detect whether a linked list contains a cycle — ByteDance uses it to confirm you reach Floyd's two-pointer trick before discussing content-graph traversal.

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

Problem

Given the head of a linked list, return true if the list has a cycle in it, otherwise return false. A cycle exists when some node can be reached again by continuously following the next pointer.

Constraints

  • 0 <= n <= 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], pos = -1
Output
false

Approaches

1. Hash set of visited nodes

Walk the list and record nodes in a set; revisit means cycle.

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

Use a slow pointer moving by one and a fast pointer moving by two. If they ever meet there is a cycle, otherwise fast hits 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:

ByteDance-specific tips

ByteDance interviewers reward candidates who explain why two-pointer dominates the hash-set approach when memory is constrained, like in their edge video transcoding pipeline.

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

Practice these live with InterviewChamp.AI →