Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Reverse List and Detect Cycles

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

Your question is Reverse List and Detect Cycles. 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

AMD compiler and runtime components may represent dependency chains as singly linked lists. Given an indexed singly linked list, detect whether it contains a cycle and reverse it in place without allocating auxiliary memory.

Use Floyd's tortoise-and-hare algorithm to detect a cycle. If a cycle exists, leave the structure unchanged and report the cycle's entry index. If the list is acyclic, reverse every link in place.

Formal Specification

Implement reverse_and_detect(values, next_indices, head), where values is an array of node payloads, next_indices[i] is the index of node i's successor, and -1 represents null. head is the starting node index. The function must return a dictionary with new_head, cycle_entry, and next_indices. Set cycle_entry to -1 for an acyclic list. The returned next_indices must reflect any in-place reversal.

Do not use sets, dictionaries for visited nodes, copied arrays, or recursion proportional to the list length.

Constraints

  • 0 <= len(values) == len(next_indices) <= 10^5
  • -1 <= next_indices[i] < len(values)
  • head is -1 or a valid node index
  • All indices reachable from head are valid
  • Node values are not used by the algorithm

Function Signature

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