#2074

Reverse Nodes in Even Length Groups

Medium
Linked ListTwo PointersLinked List Manipulation
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)

We can achieve a more efficient solution by processing the linked list in a single pass while keeping track of the group length and reversing nodes in place when needed. This reduces the number of traversals and uses less memory.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize pointers to traverse the linked list and keep track of the current group length.
  2. 2Step 2: For each group, determine its length and check if it is even.
  3. 3Step 3: If the group length is even, reverse the nodes in place by adjusting pointers.
  4. 4Step 4: Move to the next group and repeat until the end of the list.
solution.py38 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 reverseEvenLengthGroups(head):
8    if not head:
9        return head
10    current = head
11    group_length = 1
12    prev_tail = None
13    while current:
14        group_start = current
15        group_nodes = []
16        for _ in range(group_length):
17            if current:
18                group_nodes.append(current)
19                current = current.next
20        if group_length % 2 == 0:
21            # Reverse in place
22            prev = None
23            for node in group_nodes:
24                node.next = prev
25                prev = node
26            if prev_tail:
27                prev_tail.next = group_nodes[-1]
28            else:
29                head = group_nodes[-1]
30            group_nodes[0].next = current
31            prev_tail = group_nodes[0]
32        else:
33            if prev_tail:
34                prev_tail.next = group_start
35            prev_tail = group_start
36        group_length += 1
37    return head
38

Complexity note: The time complexity is O(n) because we traverse the linked list only once, and the space complexity is O(1) since we do not use any additional data structures that grow with input size.

  • 1Understanding group lengths is crucial for determining when to reverse nodes.
  • 2Reversing nodes in place is more efficient than using additional data structures.

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