Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Detect Cycle in Linked List
00:00
5 left

Detect Cycle in Linked List

MediumPython

Problem

How would you detect a cycle in a linked list?

Implement detect_cycle(nodes, head_index), where nodes[i] stores the index of the next node and -1 represents null. Return True if traversal from head_index revisits a node, otherwise return False.

Constraints

  • 0 <= len(nodes) <= 500
  • Each next-node value is either -1 or an integer from 0 through len(nodes) - 1
  • head_index is -1 for an empty list or a valid node index
  • The input represents a singly linked structure

Function Signature

def detect_cycle(nodes, head_index):
Interviewer

Your question is Detect Cycle in Linked List. Start with the requirements in the Question tab.

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.
CodePython 3
You need to log in / sign up to run or submit.Ln 2
Run your code to see test output here.