Maximum Twin Sum of a Linked List - Problem

In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th 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.

Input & Output

Example 1 — Basic Case
$ Input: head = [5,4,2,1]
Output: 6
💡 Note: Nodes (0,3) are twins with sum 5+1=6. Nodes (1,2) are twins with sum 4+2=6. Maximum is 6.
Example 2 — Different Values
$ Input: head = [4,2,2,3]
Output: 7
💡 Note: Nodes (0,3) are twins with sum 4+3=7. Nodes (1,2) are twins with sum 2+2=4. Maximum is 7.
Example 3 — Minimum Size
$ Input: head = [1,100000]
Output: 100001
💡 Note: Only one twin pair (0,1) with sum 1+100000=100001.

Constraints

  • The number of nodes in the list is in the range [2, 105].
  • 1 ≤ Node.val ≤ 105
  • The number of nodes in the list is even.

Visualization

Tap to expand
Maximum Twin Sum of a Linked List INPUT Linked List: head = [5,4,2,1] 5 i=0 4 i=1 2 i=2 1 i=3 Twin Pairs (n=4): Node 0 (val=5) twins Node 3 (val=1) Sum: 5 + 1 = 6 Node 1 (val=4) twins Node 2 (val=2) Sum: 4 + 2 = 6 Twin formula: i pairs with (n-1-i) head = [5, 4, 2, 1] ALGORITHM STEPS 1 Find Middle Use slow/fast pointers slow at node 2, fast at end 2 Reverse Second Half Reverse from middle to end [5,4] | [1,2] (reversed) 3 Calculate Twin Sums Traverse both halves together 5+1=6, 4+2=6 Twin sums: [6, 6] 4 Return Maximum Track max during traversal max(6, 6) = 6 FINAL RESULT Twin Sum Comparison: Pair 1: Node 0 + Node 3 5 + 1 = 6 Pair 2: Node 1 + Node 2 4 + 2 = 6 Maximum Twin Sum 6 Output: 6 [OK] Both pairs have same sum! Key Insight: The optimal O(n) time, O(1) space solution uses three techniques: 1) Find middle with slow/fast pointers 2) Reverse second half in-place 3) Compare corresponding pairs This avoids using extra array storage by modifying the list structure temporarily. TutorialsPoint - Maximum Twin Sum of a Linked List | Optimal Solution (Two Pointers + Reverse)
Asked in
Microsoft 15 Amazon 12 Google 8
18.5K Views
Medium Frequency
~15 min Avg. Time
825 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen