Maximum Twin Sum of a Linked List

Medium Linked Lists

Problem

Given the head of a singly linked list of even length, return the maximum twin sum of the linked list, where the twin sum is defined as the sum of the values of the ith node from the beginning and the ith node from the end.

  • The number of nodes in the list is even.
  • 2 ≤ number of nodes ≤ 10⁵
  • 1 ≤ Node.val ≤ 10⁵

Example

Input: head = [5,4,2,1]
Output: 6

The linked list has 4 nodes. The twin pairs are (5,1) and (4,2). Their sums are 6 and 6 respectively. The maximum twin sum is 6. The algorithm first finds the midpoint using slow and fast pointers. Then it reverses the second half of the list to align the twin nodes for direct comparison. Finally, it iterates through both halves simultaneously, calculating sums and tracking the maximum.

Approach

Straightforward Solution

A brute-force approach would involve converting the linked list to an array and then computing twin sums by indexing from both ends. This requires O(n) extra space and two passes, which is suboptimal for large lists.

Core Observation

The twin sum pairs correspond to nodes equidistant from the start and end of the list. To access these pairs efficiently, the list can be split into two halves, with the second half reversed to align pairs for direct traversal.

Path to Optimal

The key insight is to use the slow and fast pointer technique to find the midpoint in a single pass. Then reverse the second half of the list in-place, enabling simultaneous traversal of both halves to compute twin sums in O(n) time and O(1) space. This approach avoids extra memory and leverages linked list properties directly.

Optimal Approach

Use two pointers (slow and fast) to find the midpoint. Reverse the second half of the list starting from slow. Initialize two pointers at the start of the first half and the reversed second half. Iterate through both halves, compute sums of paired nodes, and track the maximum sum. Return the maximum twin sum found.

Time

O(n)

The algorithm traverses the list a constant number of times: once to find the midpoint, once to reverse the second half, and once to compute twin sums, each linear in the number of nodes.

Space

O(1)

All operations are done in-place with only a fixed number of pointers used, requiring constant auxiliary space regardless of input size.

Pattern Spotlight

Linked Lists (Two-Pointer Midpoint and In-Place Reversal)

To efficiently pair nodes from opposite ends of a singly linked list, find the midpoint with slow/fast pointers, reverse the second half in-place, then traverse both halves simultaneously to compute paired values without extra space.

Solution

1class Solution:
2 def pairSum(self, head: Optional[ListNode]) -> int:
3 slow = head
4 fast = head
5
6 while fast and fast.next:
7 slow = slow.next
8 fast = fast.next.next
9
10 prev = None
11
12 while slow:
13 next_node = slow.next
14 slow.next = prev
15 prev = slow
16 slow = next_node
17
18 left = head
19 right = prev
20 max_sum = 0
21
22 while right:
23 max_sum = max(max_sum, left.val + right.val)
24 left = left.next
25 right = right.next
26
27 return max_sum

Step-by-Step Solution

1

Locate Midpoint Using Slow and Fast Pointers

3slow = head
4fast = head
6while fast and fast.next:
7 slow = slow.next
8 fast = fast.next.next

Objective

To find the middle node of the linked list efficiently in a single pass.

Key Insight

Using two pointers moving at different speeds (slow moves one step, fast moves two steps) guarantees that when fast reaches the end, slow is at the midpoint. This technique exploits the linked list's sequential structure to find the midpoint without extra space or length calculation.

Interview Quick-Check

Core Logic

Slow and fast pointers traverse the list at different speeds; when fast reaches the end, slow points to the midpoint.

State & Boundaries

The loop condition `while fast and fast.next` ensures safe traversal without null pointer exceptions.

Common Pitfalls & Bugs

Incorrect loop conditions can cause infinite loops or miss the exact midpoint, especially in even-length lists.

2

Reverse the Second Half of the List In-Place

10prev = None
12while slow:
13 next_node = slow.next
14 slow.next = prev
15 prev = slow
16 slow = next_node

Objective

To reverse the nodes from the midpoint to the end, enabling direct pairing with the first half.

Key Insight

Reversing the second half in-place transforms the list so that the tail nodes become accessible in forward order. This allows simultaneous traversal of both halves to compute twin sums without extra memory. The reversal uses a standard iterative approach with three pointers to reverse links safely.

Interview Quick-Check

Core Logic

Iteratively reverse the second half by redirecting each node's next pointer to the previous node, using a temporary pointer to preserve the next node.

State & Boundaries

The loop continues until all nodes from the midpoint to the end are reversed, indicated by slow becoming null.

Common Pitfalls & Bugs

Failing to save the next node before reversing the link leads to loss of the remaining list and incorrect reversal.

3

Traverse Both Halves to Compute and Track Maximum Twin Sum

18left = head
19right = prev
20max_sum = 0
22while right:
23 max_sum = max(max_sum, left.val + right.val)
24 left = left.next
25 right = right.next

Objective

To iterate through the first half and reversed second half simultaneously, calculating twin sums and tracking the maximum.

Key Insight

With the second half reversed, corresponding twin nodes are aligned for direct access. By advancing two pointers in tandem, the algorithm computes sums of paired nodes in O(n) time. Tracking the maximum sum during traversal avoids extra passes and yields the final answer efficiently.

Interview Quick-Check

Core Logic

Simultaneous traversal of both halves allows direct computation of twin sums without extra data structures.

State & Boundaries

The loop condition `while right` ensures traversal covers all nodes in the reversed second half, which matches the first half length.

Common Pitfalls & Bugs

Not updating pointers correctly or failing to track the maximum sum can lead to incorrect results or infinite loops.

4

Return the Maximum Twin Sum Found

27return max_sum

Objective

To output the maximum twin sum after completing the traversal.

Key Insight

Returning the tracked maximum sum completes the algorithm, providing the required result. This final step is straightforward but essential to deliver the computed answer.

Interview Quick-Check

Core Logic

Return the maximum twin sum accumulated during the traversal of paired nodes.

Line Analysis

This solution has 3 Critical lines interviewers watch for.

Line 14 Critical
slow.next = prev

Reverse current node's next pointer to previous node.

This is the critical reversal step that flips the link direction, enabling backward traversal of the second half.

Line 13 Critical
next_node = slow.next

Store next node before reversing current node's pointer.

Saving next_node prevents losing access to the remainder of the list during reversal.

Line 23 Critical
max_sum = max(max_sum, left.val + right.val)

Update max_sum with maximum of current max and sum of paired nodes.

This line computes the twin sum for the current pair and updates max_sum if a larger sum is found, ensuring the final result is correct.

Line 6 Core
while fast and fast.next:

Loop while fast and fast.next are not null to find midpoint.

This condition ensures safe traversal without null pointer exceptions and guarantees slow stops at midpoint when fast reaches the end.

Line 12 Core
while slow:

Loop through second half starting at slow to reverse the list.

This loop iterates over the second half, reversing links to enable twin pairing.

Line 22 Core
while right:

Loop while right pointer is not null to traverse pairs.

Looping over right ensures traversal covers all twin pairs, as right half length matches left half.

Line 27 Core
return max_sum

Return the maximum twin sum found.

Returning max_sum completes the algorithm by outputting the final computed maximum twin sum.

Line 3 Core
slow = head

Initialize slow pointer at the head of the list.

Starting slow at head sets up the two-pointer technique to find the midpoint by moving at half the speed of fast.

Line 4 Core
fast = head

Initialize fast pointer at the head of the list.

Fast pointer moves twice as fast as slow, enabling midpoint detection when fast reaches the end.

Line 10 Core
prev = None

Initialize previous pointer to None for reversal.

Prev pointer tracks the reversed portion of the list, starting empty before reversal begins.

Line 15 Core
prev = slow

Move previous pointer to current node.

Prev advances to include the newly reversed node, building the reversed list incrementally.

Line 16 Core
slow = next_node

Advance slow pointer to next node to continue reversal.

Slow moves forward to process the next node in the original second half.

Line 19 Core
right = prev

Initialize right pointer at head of reversed second half.

Right pointer traverses reversed second half, aligned with left for twin sum calculation.

Line 24 Core
left = left.next

Advance left pointer to next node in first half.

Moving left forward aligns it with the next twin node for the next iteration.

Line 25 Core
right = right.next

Advance right pointer to next node in reversed second half.

Moving right forward aligns it with the next twin node for the next iteration.

Line 7 Standard
slow = slow.next

Advance slow pointer by one node.

Slow pointer moves one step per iteration, progressing towards the midpoint.

Line 8 Standard
fast = fast.next.next

Advance fast pointer by two nodes.

Fast pointer moves two steps per iteration, moving twice as fast as slow to detect midpoint.

Line 18 Standard
left = head

Initialize left pointer at head of the list.

Left pointer traverses the first half to pair with reversed second half nodes.

Line 20 Standard
max_sum = 0

Initialize max_sum to zero to track maximum twin sum.

max_sum stores the highest twin sum found during traversal, starting from zero.

Test Your Understanding

Why is reversing the second half of the linked list necessary for computing the twin sums efficiently?

Reversing the second half aligns the nodes from the end of the list in forward order, allowing simultaneous traversal of both halves to access twin pairs directly without extra space or multiple passes.

Related Problems

Linked Lists pattern

Don't just read it. Drill it.

Reconstruct Maximum Twin Sum of a Linked List from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.

Unlock the Maximum Twin Sum of a Linked List drill

or drill a free problem