You are given the head of a singly linked list and two integers left and right. Your task is to reverse the nodes from position left to position right (1-indexed) while keeping the remaining nodes unchanged.
Example 1
Input: head = [1,2,3,4,5], left = 2, right = 4
Output: [1,4,3,2,5]
Explanation: The nodes from positions 2 to 4 are reversed, while the rest of the linked list remains unchanged.
Example 2
Input: head = [5], left = 1, right = 1
Output: [5]
Explanation: Since the sublist contains only one node, the linked list remains unchanged.
Example 3
Input: head = [1,2,3,4,5,6], left = 3, right = 6
Output: [1,2,6,5,4,3]
Explanation: The nodes from positions 3 to 6 are reversed.
Approach, complexity and clean code in every language. Sign in to unlock the editorial.
Your submissions, results and runtime history live here. Sign in to start your streak.
1 2 3 4 5 2 4
1 4 3 2 5
1 2 3 4 5 1 5
5 4 3 2 1