SDE & MLE Prep

92. Reverse Linked List II

Problem

Reverse the nodes from position left to position right (1-based, inclusive) and return the head.

Example: 1→2→3→4→5, left = 2, right = 4 → 1→4→3→2→5

Constraints: follow-up: one pass.

Walk to the node before left. Then repeatedly move the node after cur to the front of the sublist (right − left times) — "head insertion".

1 [2 3 4] 5   left=2 right=4
1 [3 2 4] 5   move 3 to front
1 [4 3 2] 5   move 4 to front

Complexity: O(n) time, O(1) space.

class Solution:
    def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
        dummy = ListNode(0, head)
        prev = dummy
        for _ in range(left - 1):
            prev = prev.next
        cur = prev.next
        for _ in range(right - left):
            nxt = cur.next
            cur.next = nxt.next
            nxt.next = prev.next
            prev.next = nxt
        return dummy.next