Dataford
Interview QuestionsInterview GuidesExperiencesCoaching
New
Pricing
Get started
Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
ExperiencesCoaching
New
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Get started
Reverse List and Detect Cycles
00:00
5 left

Reverse List and Detect Cycles

MediumPython

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):
Interviewer

Your question is Reverse List and Detect Cycles. 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.
Code
Sign up free to run your codeLog inLn 2
Run your code to see test output here.