Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Detect Loop in Linked List

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

Your question is Detect Loop in Linked List. 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

SIXT represents a sequence of vehicle records as a singly linked list. Detect whether following the next references eventually revisits a node, which indicates a cycle.

For portability, the linked list is encoded by an array next, where next[i] is the index of the node reached from node i, or -1 if the node has no successor. The list begins at head.

Return True if the list contains a cycle, otherwise return False. Do not modify the input.

Formal Specification

Implement has_cycle(next, head):

  • next: a list of integers representing successor indices.
  • head: an integer node index, or -1 for an empty list.
  • Return: a Boolean indicating whether any node can be reached again by following successors.

Use constant auxiliary space. The cycle may begin at the head or at any later node.

Constraints

  • 0 <= len(next) <= 10^5
  • head is -1 or a valid index in next
  • Each successor is -1 or a valid index in next
  • Each node has at most one successor

Function Signature

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