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: Transform Specific SectionInput:12345left=2right=4⬇ Reverse section from position 2 to 4 ⬇Output:14325Reversed section
Understanding the Visualization
1
Input
Linked list [1,2,3,4,5] with left=2, right=4
2
Process
Reverse nodes from position 2 to 4
3
Output
Resulting list [1,4,3,2,5]
Key Takeaway
🎯 Key Insight: Use three pointers to reverse links while maintaining connections to unreversed parts
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