MediumNo. 0092
Reverse Linked List II — LeetCode 92 Python Solution
- Pattern
- Linked List
- Topics
- Linked List
- On a study list
- Top Interview 150
- Reading time
- 4 min
- Source
- leetcode.com
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
# 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.nextComplexity
- 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
| No. | Problem | Difficulty |
|---|---|---|
| 0206 | Reverse Linked List | Easy |
| 0086 | Partition List | Medium |
| 0083 | Remove Duplicates from Sorted List | Easy |
| 0082 | Remove Duplicates from Sorted List II | Medium |
| 0019 | Remove Nth Node From End of List | Medium |
| 0021 | Merge Two Sorted Lists | Easy |
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.