Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Detect a Linked List Loop

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Detect a Linked List Loop. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

An Equifax security-review workflow is represented as a singly linked chain. Detect whether following the next reference from the starting node eventually revisits a node.

Implement has_cycle(next_indices, head). Use Floyd's tortoise-and-hare technique and require constant extra space.

Formal Specification

  • next_indices is an array where index i represents a node.
  • next_indices[i] is the index of the next node, or -1 if node i terminates the chain.
  • head is the starting node index, or -1 for an empty chain.
  • Return True if a cycle is reachable from head; otherwise return False.

Constraints

  • 0 <= len(next_indices) <= 100,000
  • Each next_indices[i] is -1 or an index from 0 to len(next_indices) - 1
  • head is -1 or an index from 0 to len(next_indices) - 1
  • Use O(1) auxiliary space

Function Signature

def has_cycle(next_indices, head):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output