Leetcode 92: Reverse Linked List II

grid47
grid47
Exploring patterns and algorithms
Oct 28, 2024 6 min read

A linked list gently reversing, glowing softly with each node that changes position.
Solution to LeetCode 92: Reverse Linked List II Problem

Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the linked list starting at position left and ending at position right. Return the modified linked list.
Problem
Approach
Steps
Complexity
Input: The function receives the head of a singly linked list and two integers `left` and `right` representing the positions in the list to reverse.
Example: Input: head = [7,9,11,5,2], left = 3, right = 5
Constraints:
• The number of nodes in the list is n.
• 1 <= n <= 500
• -500 <= Node.val <= 500
• 1 <= left <= right <= n
Output: Return the head of the modified singly linked list after reversing the specified section.
Example: Output: [7,9,2,5,11]
Constraints:
• The output list retains all nodes from the original list.
• The reversed portion is accurately modified while the rest remains untouched.
Goal: Reverse the nodes of a singly linked list between positions `left` and `right` in a single traversal.
Steps:
• Create a dummy node pointing to the head of the list.
• Traverse to the node immediately before position `left`.
• Perform in-place node re-linking to reverse the sublist between `left` and `right`.
• Reconnect the reversed sublist to the remaining parts of the list.
Goal: Ensure proper handling of edge cases and valid inputs.
Steps:
• Handle lists with a single node or where `left == right`.
• Ensure the function operates within O(1) space complexity apart from the input list.
Assumptions:
• The input list is non-circular and contains valid node values.
• `left` and `right` are always within valid bounds.
Input: Input: head = [3,6,1,8,5], left = 2, right = 4
Explanation: Reverse the sublist from position 2 to 4. Resulting list is [3,8,1,6,5].

Input: Input: head = [10], left = 1, right = 1
Explanation: Since the list contains a single node and `left == right`, the list remains [10].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus