Skip to problem
←

Reverse Linked List II

Medium 0 attempts

Given a nonempty singly linked list and two 1-based positions left and right, reverse the nodes in that inclusive segment and return the resulting head.

Rewire the original nodes without changing their values or creating replacements. Keep the nodes before and after the selected segment in their original order. If left = right, the list is unchanged. If left = 1, the head may change.

For [1, 2, 3, 4, 5], left = 2, and right = 4, return [1, 4, 3, 2, 5]. These numbers specify positions, not values to search for.

Your function receives nodes with val and next properties; examples display value arrays. Use constant extra space.

Function contract

Implement reverseBetween(head, left, right). Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.

Output: Return the head after reversing the original nodes at positions left through right, inclusive. Preserve all node values and the order outside that segment.

Example 1

Input
head = [1,2,3,4,5]
left = 2
right = 4
Output
[1,4,3,2,5]

Example 2

Input
head = [1]
left = 1
right = 1
Output
[1]
Constraints
  • 1 <= n <= 500
  • -500 <= Node.val <= 500
  • 1 <= left <= right <= n
Topics

Move Each Next Node to the Segment Front

Use a dummy head and move prev to the node immediately before position left. Keep curr at the first node of the segment; it will become the segment's tail.

Repeat right - left times: detach the node immediately after curr, then insert it immediately after prev. Each move extends the reversed prefix by one node while curr remains in place as its tail.

The dummy makes a segment starting at the head work identically. The nodes outside the segment keep their order, and returning dummy.next supplies the possibly changed head. When both positions are equal, no moves are needed.

javascript
function reverseBetween(head, left, right) {
  const dummy = { next: head };
  let prev = dummy;
  for (let i = 0; i < left - 1; i++) prev = prev.next;
  let curr = prev.next;
  for (let i = 0; i < right - left; i++) {
    const next = curr.next;
    curr.next = next.next;
    next.next = prev.next;
    prev.next = next;
  }
  return dummy.next;
}

Time: O(n) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript