Maximum Twin Sum of a Linked List (LeetCode 2130): Solution and Explanation
In an even-length linked list, node i and node n - 1 - i are twins. Return the largest value of a node plus its twin. The O(1)-space solution finds the middle, reverses the second half and walks both halves side by side.
Intuition
The pairs are mirror images: the first node pairs with the last, the second with the second to last, and so on. With an array you would put one index at each end and move them toward each other, but a singly linked list cannot walk backwards from the tail.
The fix is to make the second half walk the right way. If you reverse the second half, its new head is the old tail, the next node is the one before the tail, and so on. Now the first half read forwards and the reversed second half read forwards line up exactly as twins.
Finding where the second half starts is the classic slow and fast pointer race: fast moves two nodes per step, slow moves one, and when fast runs off the end slow is on node n / 2, the first node of the second half.
Approach: Find the middle, reverse the second half, walk the twins
- Start
slowandfastat head. Whilefastandfast.nextexist, move slow one node and fast two nodes. slow ends on node n / 2. - Reverse the list that starts at
slow: for each node, save its next, point it atprev, then moveprevandslowforward.prevends on the old tail. - Walk
headandprevtogether. At each stephead.val + prev.valis one twin sum; keep the largest. - Stop when
prevbecomes null and return the best sum.
Step-by-step example
head = [5,4,2,1]
- slow and fast start on 5. fast and fast.next exist, so slow moves to 4 and fast moves to 2.
- fast is on 2 and fast.next is 1, so slow moves to 2 and fast moves past the tail to null. slow is on 2, index 2 = n / 2.
- Reverse from 2: node 2 points to null, then node 1 points to 2. prev is now 1, so the second half reads 1, 2.
- First pair: head is 5, prev is 1, sum 6, best = 6.
- Second pair: head is 4, prev is 2, sum 6, best stays 6. prev becomes null, so return 6.
Code: Python, Java, C++
1class Solution:
2 def pairSum(self, head: Optional[ListNode]) -> int:
3 slow, fast = head, 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 while prev:
15 best = max(best, head.val + prev.val)
16 head = head.next
17 prev = prev.next
18 return best1class Solution {
2 public int pairSum(ListNode head) {
3 ListNode slow = head, fast = head;
4 while (fast != null && fast.next != null) {
5 slow = slow.next;
6 fast = fast.next.next;
7 }
8 ListNode prev = null;
9 while (slow != null) {
10 ListNode nxt = slow.next;
11 slow.next = prev;
12 prev = slow;
13 slow = nxt;
14 }
15 int best = 0;
16 while (prev != null) {
17 best = Math.max(best, head.val + prev.val);
18 head = head.next;
19 prev = prev.next;
20 }
21 return best;
22 }
23}1class Solution {
2public:
3 int pairSum(ListNode* head) {
4 ListNode *slow = head, *fast = head;
5 while (fast && fast->next) {
6 slow = slow->next;
7 fast = fast->next->next;
8 }
9 ListNode* prev = nullptr;
10 while (slow) {
11 ListNode* nxt = slow->next;
12 slow->next = prev;
13 prev = slow;
14 slow = nxt;
15 }
16 int best = 0;
17 while (prev) {
18 best = max(best, head->val + prev->val);
19 head = head->next;
20 prev = prev->next;
21 }
22 return best;
23 }
24};Time and space complexity
O(n)
The pointer race visits about n / 2 nodes, the reversal touches n / 2 nodes and the final walk visits n / 2 pairs.
O(1)
Only a handful of pointers and one integer. The reversal reuses the existing nodes.
Other approaches
Copy values into an array (time O(n), space O(n))
Read every value into an array, then use two indices from both ends and take the largest a[i] + a[n - 1 - i]. It is the simplest code and easy to get right, but it uses O(n) extra memory.
Stack of the first half (time O(n), space O(n))
Push the first n / 2 values onto a stack, then walk the second half and pop one value per node. The pop order is reversed, so each popped value is the twin of the current node. It avoids changing the list but still needs O(n) space.
Common mistakes
- Starting fast at head.next instead of head. That leaves slow on node n / 2 - 1, the last node of the first half, so the pairs come out shifted by one.
- Losing the rest of the list during the reversal by writing
slow.next = prevbefore savingslow.next. - Looping on
headinstead ofprevin the final walk. The first half still links into the second half, so head would keep going past the twins. - Leaving the list modified when the caller expects it intact. If that matters, reverse the second half back before returning.
Frequently asked questions
Why does slow land on the first node of the second half?
Both pointers start on head and fast moves twice as far. For even n, fast becomes null after n / 2 steps, and by then slow has moved n / 2 nodes, so it sits on index n / 2.
Do I need to cut the first half off from the second half?
No. The first half's last node still points into the reversed part, but the final loop stops when prev becomes null, and prev only ever walks the reversed second half, which ends in null.
Can the answer overflow a 32-bit integer?
No. Each value is at most 100000, so a twin sum is at most 200000.
Is this the same trick as Palindrome Linked List?
Yes. Palindrome Linked List also finds the middle and reverses the second half, then compares values for equality instead of adding them.