KatInterview

92. Reverse Linked List II

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires us to reverse a portion of a linked list from a given start position left to an end position right. The key challenges are:

Solution

Reverse Linked List II in Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
        if left == right:
            return head

        # Create a dummy node to simplify edge cases like reversing from the head.
        dummy = ListNode(0, head)

        # 1. Move `pre_left` to the node just before the reversal section.
        pre_left = dummy
        for _ in range(left - 1):
            pre_left = pre_left.next

        # 2. `current` points to the first node of the reversal section.
        # This node will become the tail of the reversed section.
        current = pre_left.next

        # 3. Iteratively reverse the sublist.
        # In each step, move the node after `current` to the front of the reversed section.
        for _ in range(right - left):
            node_to_move = current.next
            current.next = node_to_move.next
            node_to_move.next = pre_left.next
            pre_left.next = node_to_move

        return dummy.next

Reverse Linked List II in Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        if (left == right) {
            return head;
        }

        // Create a dummy node to simplify edge cases like reversing from the head.
        ListNode dummy = new ListNode(0, head);

        // 1. Move `preLeft` to the node just before the reversal section.
        ListNode preLeft = dummy;
        for (int i = 0; i < left - 1; i++) {
            preLeft = preLeft.next;
        }

        // 2. `current` points to the first node of the reversal section.
        // This node will become the tail of the reversed section.
        ListNode current = preLeft.next;

        // 3. Iteratively reverse the sublist.
        // In each step, move the node after `current` to the front of the reversed section.
        for (int i = 0; i < right - left; i++) {
            ListNode nodeToMove = current.next;
            current.next = nodeToMove.next;
            nodeToMove.next = preLeft.next;
            preLeft.next = nodeToMove;
        }

        return dummy.next;
    }
}

Reverse Linked List II in C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        if (left == right) {
            return head;
        }

        // Create a dummy node to simplify edge cases like reversing from the head.
        ListNode* dummy = new ListNode(0, head);

        // 1. Move `pre_left` to the node just before the reversal section.
        ListNode* pre_left = dummy;
        for (int i = 0; i < left - 1; ++i) {
            pre_left = pre_left->next;
        }

        // 2. `current` points to the first node of the reversal section.
        // This node will become the tail of the reversed section.
        ListNode* current = pre_left->next;

        // 3. Iteratively reverse the sublist.
        // In each step, move the node after `current` to the front of the reversed section.
        for (int i = 0; i < right - left; ++i) {
            ListNode* node_to_move = current->next;
            current->next = node_to_move->next;
            node_to_move->next = pre_left->next;
            pre_left->next = node_to_move;
        }
        
        // The new head is dummy->next. We must store it before deleting dummy.
        ListNode* new_head = dummy->next;
        delete dummy;
        return new_head;
    }
};

Reverse Linked List II in TypeScript

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function reverseBetween(head: ListNode | null, left: number, right: number): ListNode | null {
    if (left === right) {
        return head;
    }

    // Create a dummy node to simplify edge cases like reversing from the head.
    const dummy = new ListNode(0, head);

    // 1. Move `preLeft` to the node just before the reversal section.
    let preLeft: ListNode | null = dummy;
    for (let i = 0; i < left - 1; i++) {
        preLeft = preLeft!.next;
    }

    // 2. `current` points to the first node of the reversal section.
    // This node will become the tail of the reversed section.
    let current = preLeft!.next;

    // 3. Iteratively reverse the sublist.
    // In each step, move the node after `current` to the front of the reversed section.
    // Constraints ensure `current` and `current.next` will be valid within the loop.
    for (let i = 0; i < right - left; i++) {
        const nodeToMove = current!.next;
        current!.next = nodeToMove!.next;
        nodeToMove!.next = preLeft!.next;
        preLeft!.next = nodeToMove;
    }

    return dummy.next;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.