MediumNo. 0092

Reverse Linked List II — LeetCode 92 Python Solution

Topics
Linked List
On a study list
Top Interview 150
Reading time
4 min

The 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.

Example

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

Python solution

PythonSolution
# 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 head.next is None or left == right:
            return head
        dummy = ListNode(0, head)
        pre = dummy
        for _ in range(left - 1):
            pre = pre.next
        p, q = pre, pre.next
        cur = q
        for _ in range(right - left + 1):
            t = cur.next
            cur.next = pre
            pre, cur = cur, t
        p.next = pre
        q.next = cur
        return dummy.next

Complexity

Time
O(n)
Space · auxiliary
O(1)

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 92. Reverse Linked List II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Linked List.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 92. Reverse Linked List II?

LeetCode 92. Reverse Linked List II is rated Medium on LeetCode.

What is the time complexity of LeetCode 92. Reverse Linked List II?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 92. Reverse Linked List II?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 92. Reverse Linked List II cover?

LeetCode 92. Reverse Linked List II is tagged Linked List on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.