LeetCode #2130 Medium

Maximum Twin Sum of a Linked List

Maximum Twin Sum of a Linked List is LeetCode 2130 (Medium). A singly linked list has an even number of nodes, n. Counting from 0, node i and node n - 1 - i are twins: the first and the last, the second and the second-to-last, and so on. Return the largest value of a node plus its twin.

  • The list has between 2 and 100,000 nodes, each holding a value from 1 to 100,000.
  • Each node only knows the node after it, so the end of the list cannot be reached from the front without walking the whole way.
Constraints
  • The number of nodes is an even integer in the range [2, 10⁵].
  • 1 <= Node.val <= 10⁵
linked-listtwo-pointersstack
Open on LeetCode ↗
02

Intuition

Twins sit at mirror positions: the first half read forwards lines up with the second half read backwards. A singly linked list cannot be read backwards, so reverse the second half in place and the problem becomes a walk down two lists side by side.

  • Find the middle: move a fast pointer two nodes per step and a slow pointer one. When the fast one runs off the end, the slow one stands on the first node of the second half.
  • Reverse: flip the links of the second half, so its last node becomes its head.
  • Pair up: start one pointer at the head and one at the old last node. Each step lands them on a pair of twins.
How to spot this pattern

Pairing the front of a singly linked list with its back (palindrome checks, twin sums, folding a list) almost always means: find the middle with slow and fast pointers, reverse the second half, then walk both halves together.

03

Approach

Try it first

Before reading on, work out where a slow pointer (one step) and a fast pointer (two steps) stop on a list of 4 nodes and on a list of 6 nodes. Aim for O(n) time and O(1) extra space.

1

Find the first node of the second half

Start slow and fast at the head. While fast and fast.next both exist, move slow one node and fast two. With an even count, fast runs off the end exactly when slow reaches node n / 2, the first node of the second half.

2

Reverse the second half

Walk from slow to the end, pointing each node's next back at the node before it (prev). When the walk ends, prev is the old last node, now the head of the reversed half.

3

Walk both halves together

Set first = head and second = prev. On each step add first.val + second.val, keep the maximum, and move both pointers forward. Stop when second runs out.

4

Why the pointers always land on twins

After k steps, first is on node k from the front and second is on node k from the back, which is node n - 1 - k. Those two nodes are twins by definition, so every pair gets checked exactly once.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def pairSum(self, head):
▶3 slow = fast = head
▶4 while fast and fast.next:
▶5 slow = slow.next
▶6 fast = fast.next.next
▶7 prev = None
▶8 while slow:
▶9 nxt = slow.next
▶10 slow.next = prev
▶11 prev = slow
▶12 slow = nxt
▶13 best = 0
▶14 first, second = head, prev
▶15 while second:
▶16 best = max(best, first.val + second.val)
▶17 first, second = first.next, second.next
▶18 return best
4223slow, fasttwin sumbestslow and fast start at the head
n4even
slownode 0
fastnode 0
The twins are node 0 with node 3, node 1 with node 2, and so on. To reach the back of the list, first find where the second half starts.
4223slowfasttwin sumbestslow moves 1, fast moves 2
slownode 1
fastnode 2
Fast moves twice as far as slow, so when fast reaches the end, slow will be halfway.
4223slowtwin sumbestfast ran off the end → second half starts at slow
slownode 2
fastpast the end
Fast covered 4 nodes while slow covered 2, so slow now stands on node 2, the first node of the second half (shaded green).
4223prevslowtwin sumbestnode 2 now points to nothing
prevnode 2
slownode 3
Node 2 will be the last node of the reversed half, so its link is cut. The node before it in the first half still points to it, which is harmless.
4223prevtwin sumbestnode 3 now points back to node 2
prevnode 3
slowpast the end
Node 3's link is flipped to point back at node 2. That was the last node, so node 3 is the head of the reversed half.
4223firstsecondtwin sumbest4+3=77node 0 + node 3 = 7 → new best
twinsnode 0, node 3
sum7
best7
First is 0 steps from the front and second is 0 steps from the back, so they are twins. Their sum is 7, the largest so far.
4223firstsecondtwin sumbest2+2=47node 1 + node 2 = 4 → best stays 7
twinsnode 1, node 2
sum4
best7
First is 1 step from the front and second is 1 step from the back, so they are twins. Their sum is 4, which does not beat 7.
4223twin sumbest7answer: 7
return7
Second has run off the end of the reversed half, so all 2 pairs of twins were checked. The largest twin sum is 7.
05

Common pitfalls

Checking only fast.next in the middle loop

✗ Wrong
while fast.next:
✓ Right
while fast and fast.next:

On an even list, the last jump sets fast to None, and the next check reads None.next. On [5, 4, 2, 1] this crashes after the second step.

Stopping the pairing loop on the first pointer

✗ Wrong
while first:
✓ Right
while second:

The last node of the first half still points at the first node of the second half, so the front walk sees n / 2 + 1 nodes while the reversed half has only n / 2. On [1, 100000] the loop runs a second time with second already None and crashes.

06

Edge cases

Only two nodes, as in [1, 100000]

slow stops on the second node, the reversed half is that single node, and the one pair gives 100001.

07

Complexity

Time
O(n)
Space
O(1)
Finding the middle, reversing and pairing each walk at most n nodes. Only a handful of pointers are stored, because the reversal reuses the existing nodes.
08

Maximum Twin Sum of a Linked List FAQ

Is it all right to change the input list?

The judge only checks the returned number, so leaving the second half reversed is accepted. If the caller still needs the list, reverse the second half again after pairing and the original order comes back, still in O(1) space.

Is there a simpler way if extra memory is allowed?

Copy the values into an array and take the largest vals[i] + vals[n - 1 - i] for i below n / 2. Another option pushes the first half onto a stack while the slow and fast pointers move, then pops one value per node of the second half. Both take O(n) extra space but avoid relinking nodes.