Notes & software courses · Free to learn
Aph's Blog

LC2130 Maximum Twin Sum of a Linked List 🟡

👋 อ่านฟรีทั้งหมดบน Aph's Blog — เนื้อหาภาษาไทย ทำตามทีละหน้าใน sidebar ได้เลย หากมีข้อเสนอแนะหรืออยากให้เพิ่มหัวข้อไหน บอกได้เสมอ

Compose three moves: Fast & Slow to the middle → reverse the second half → walk both halves and track the max twin sum.

In a linked list of size n, where n is even, the iᵗʰ node (0-indexed) of the linked list is known as the twin of the (n-1-i)ᵗʰ node, if 0 <= i <= (n / 2) - 1.

- For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only nodes with twins for n = 4.

The twin sum is defined as the sum of a node and its twin.

Given the head of a linked list with even length, return the maximum twin sum of the linked list.

Example 1
Input:
head = [5,4,2,1]
Output:
6
Explanation:
Explanation:
Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.
There are no other nodes with twins in the linked list.
Thus, the maximum twin sum of the linked list is 6.
Example 2
Input:
head = [4,2,2,3]
Output:
7
Explanation:
Explanation:
The nodes with twins present in this linked list are:
- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.
- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.
Thus, the maximum twin sum of the linked list is max(7, 4) = 7.
Example 3
Input:
head = [1,100000]
Output:
100001
Explanation:
Explanation:
There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.
Constraints (ข้อจำกัด)
  • The number of nodes in the list is an even integer in the range [2, 10^5].
  • 1 <= Node.val <= 10^5
Full solution · Try yourself firstพับไว้ด้านใน — คลิกเมื่อพร้อมดู

This is the boss fight of the section — compose three moves from earlier problems: Fast & Slow (p29) + Reverse (p31) + walk two chains.

1. Mindset Shift

The hard part: a linked list can’t walk backward — adding a front node to its twin at the back is awkward.

Key insight: find the middle with Fast & Slow → reverse the second half so it faces the same way as the first → walk from both ends and track the max twin sum.

The easy way is dump every value into a list and add vals[i] + vals[n-1-i] — correct but Space O(n). This approach stays in-place at Space O(1).

2. The Logic — 3 Steps

Split the work into three clear stages:

  1. Find middle — Fast & Slow walk; when fast falls off, slow sits at the head of the second half (n is always even)
  2. Reverse second half — reuse the p31 flip from slow; prev becomes the new head (the old last node moves to the front)
  3. Pair and add — first at head · second at prev; walk together; first.val + second.val is one twin sum; keep the max

3. LeetCode-Ready Code

Three stages lined up in one function:

Submit this on LeetCodepython
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def pairSum(self, head: Optional[ListNode]) -> int:
        # Stage 1: find middle with Fast & Slow
        slow = head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        # slow is now the head of the second half

        # Stage 2: reverse the second half (p31 move)
        prev = None
        cur = slow
        while cur:
            nxt = cur.next
            cur.next = prev
            prev = cur
            cur = nxt
        # prev is the head of the reversed second half

        # Stage 3: walk both halves, track max twin sum
        best = 0
        first = head
        second = prev
        while second:               # halves are the same length
            best = max(best, first.val + second.val)
            first = first.next
            second = second.next
        return best

4. Dry Run — 5 → 4 → 2 → 1

StageStateResultlist now
Start5 → 4 → 2 → 1
Find middlefast falls off · slow stops at 2slow = second-half head5 → 4 | 2 → 1
Reverse round 1cur=2 · flip next → Noneprev=25 → 4 | None ← 2 | 1
Reverse round 2cur=1 · flip next → 2prev=1 = new head5 → 4 | 1 → 2
Pair 1first=5 · second=15+1 = 6 · best = 65 → 4 | 1 → 2
Pair 2first=4 · second=24+2 = 6 · best = 64 | 2
Donesecond is Nonereturn best = 6answer = 6

The | mark splits pieces: left = first half · right = second half (being reversed / paired) — final answer 6

5. Edge Cases & Pitfalls

The "crossed link at the midpoint" case:

  • After reversing the second half, the link at the midpoint may look a bit crossed
  • It doesn’t matter — we only walk n/2 steps and stop when second is None
Is best = 0 OK?

Yes — this problem guarantees positive node values. If negatives were allowed, start from the first pair instead.

6. Time & Space Complexity

  • Time O(n) — find middle + reverse second half + pair walk are all linear
  • Space O(1) — rewire in place; no copy into a new list
💡 Pattern summary

Hard linked-list problems are often compositions of basic moves (find middle + reverse + walk two chains) — if each move is solid, assembling the puzzle gets much easier.