#92

Reverse Linked List II

Medium
Linked ListTwo PointersIn-Place Reversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach reverses the sublist in place without needing to extract it first. This reduces the time complexity significantly and allows us to do it in one pass.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a dummy node to simplify edge cases and find the node just before the 'left' position.
  2. 2Step 2: Reverse the nodes between 'left' and 'right' using a loop.
  3. 3Step 3: Reconnect the reversed sublist to the original list.
solution.py21 lines
1# Full working Python code
2class ListNode:
3    def __init__(self, val=0, next=None):
4        self.val = val
5        self.next = next
6
7def reverseBetween(head: ListNode, left: int, right: int) -> ListNode:
8    if not head or left == right:
9        return head
10    dummy = ListNode(0, head)
11    prev = dummy
12    for _ in range(left - 1):
13        prev = prev.next
14    curr = prev.next
15    tail = curr
16    for _ in range(right - left):
17        temp = curr.next
18        curr.next = temp.next
19        temp.next = prev.next
20        prev.next = temp
21    return dummy.next

Complexity note: The time complexity is O(n) because we traverse the list only once to find the nodes and reverse them in place, and the space complexity is O(1) since we are using a constant amount of extra space.

  • 1Reversing a linked list can be done in place, which is more efficient.
  • 2Using a dummy node simplifies edge cases when modifying the head of the list.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.