Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Reverse Linked List Between Positions

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

Your question is Reverse Linked List Between Positions. 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

Freshdesk can represent an ordered chain of ticket-processing steps as a singly linked list. Given the chain's head and two 1-indexed positions, reverse the nodes from left through right while preserving every node outside that range.

Implement reverse_between(head, left, right) and return the new head. The reversal must be performed by changing pointers, not by creating replacement nodes or copying values.

Formal Specification

  • head is either the first ListNode in a singly linked list or None.
  • Each ListNode has an integer val field and a next field.
  • left and right are valid 1-indexed positions, with left <= right.
  • Return the head of the modified linked list.
  • Test cases represent linked lists as arrays of values for readability. The evaluator converts each array into a linked chain before calling the function and converts the result back to an array.

Constraints

  • 0 <= number of nodes <= 500
  • -500 <= node.val <= 500
  • 1 <= left <= right <= number of nodes
  • The list is singly linked
  • Reverse nodes by changing pointers, without creating replacement nodes

Function Signature

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