Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Linked List Reverse or Cycle

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

Your question is Linked List Reverse or Cycle. 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

People's QA checks sometimes model workflow transitions as a linked sequence of states. Given an array representation of those transitions, determine whether the sequence starting at head eventually loops back to a previously visited state.

Each array index represents one state, and next_indices[i] gives the index of the next state. A value of -1 indicates the end of the sequence. Return True if a cycle exists and False otherwise. Solve the problem with O(1) additional space using two pointers moving at different speeds.

Formal Specification

Implement detect_cycle(next_indices, head).

  • Input: next_indices, a list of integers, and head, an integer index. Each pointer is either -1 or a valid index in next_indices.
  • Output: A boolean indicating whether the linked sequence contains a cycle.
  • The input represents a singly linked list, where each state has at most one outgoing transition.

Constraints

  • 0 <= len(next_indices) <= 10^5
  • head is -1 or a valid index in next_indices
  • Every next_indices[i] is -1 or a valid index
  • Only states reachable from head affect the result

Function Signature

def detect_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