Reverse Linked List II — LeetCode 92 Python Solution
- Problem
- #92
- Pattern
- Linked List
- 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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) auxiliary |
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
On a study list
This problem is on Top Interview 150.
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.