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 list from position left to position right, and return the reversed list.

The positions are 1-indexed.

Input & Output

Example 1 — Basic Reversal
$ Input: head = [1,2,3,4,5], left = 2, right = 4
Output: [1,4,3,2,5]
💡 Note: Reverse nodes from position 2 to 4: 2→3→4 becomes 4→3→2, while nodes 1 and 5 remain in place
Example 2 — Single Node
$ Input: head = [5], left = 1, right = 1
Output: [5]
💡 Note: Only one node and reversing position 1 to 1 means no change needed
Example 3 — Full List Reversal
$ Input: head = [3,5], left = 1, right = 2
Output: [5,3]
💡 Note: Reverse the entire list from position 1 to 2: 3→5 becomes 5→3

Constraints

  • The number of nodes in the list is n
  • 1 ≤ n ≤ 500
  • -500 ≤ Node.val ≤ 500
  • 1 ≤ left ≤ right ≤ n

Visualization

Tap to expand
Reverse Linked List II INPUT Original Linked List: 1 2 3 4 5 = Nodes to reverse Parameters: head = [1,2,3,4,5] left = 2 right = 4 Reverse positions 2 to 4 ALGORITHM STEPS 1 Find Position Move to node before left 1 ^prev 2 Set Pointers curr = node at left 2 ^curr 3 Reverse Links Move next nodes to front next = curr.next curr.next = next.next next.next = prev.next prev.next = next 4 Repeat Loop (right-left) times Iterations: 4-2 = 2 FINAL RESULT Reversed Linked List: 1 4 3 2 5 = Reversed section Output: [1, 4, 3, 2, 5] OK - Reversed! Positions 2-4 reversed Key Insight: One-pass pointer reversal works by repeatedly moving the next node after 'curr' to the front of the reversed section. This avoids the need for extra space and achieves O(n) time complexity. Time: O(n) | Space: O(1) - Only constant extra pointers needed TutorialsPoint - Reverse Linked List II | One-Pass Pointer Reversal Approach
Asked in
Facebook 45 Amazon 38 Microsoft 32 Google 28
587.0K Views
High Frequency
~15 min Avg. Time
8.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen