InterviewPrepKit

Home / Coding / Linked List

Maximum Twin Sum of a Linked List

medium Original β†—
Solving tips
  • Twins pair position i with n-1-i, i.e. the first half against the reversed second half aligned position by position.
  • Three-step kit: find the middle with slow/fast pointers, reverse the second half in place, then sweep both halves in lockstep taking the max sum; O(n) time, O(1) space.
  • Bound the final loop by the reversed-second-half pointer (n/2 steps), not the first-half pointer, which may still run into the severed half.
  • An O(n)-space shortcut is to copy values into an array and pair index i with n-1-i, but the reverse-half method is the O(1)-space answer interviewers want.

Problem

You are given the head of a singly linked list with an even number of nodes, n. Pair up the nodes symmetrically from the two ends: the node at position i (0-indexed) is the twin of the node at position n - 1 - i. So the first node is twinned with the last, the second with the second-to-last, and so on β€” every node has exactly one twin.

The twin sum of a pair is the sum of the two twins’ values. Return the maximum twin sum over all pairs in the list.

Examples

  • Input: head = [5, 4, 2, 1] β†’ Output: 6 Pairs are (5,1) and (4,2); both sum to 6, so the max is 6.
  • Input: head = [4, 2, 2, 3] β†’ Output: 7 Pairs are (4,3)=7 and (2,2)=4; the max is 7.
  • Input: head = [1, 100000] β†’ Output: 100001 Only one pair exists: (1, 100000).

Constraints

  • The number of nodes n is even and 2 <= n <= 10^5.
  • 1 <= Node.val <= 10^5.

The linear size means anything quadratic (re-walking the list for every node) is too slow; aim for O(n) time.

Think about it first

Hint 1 If the values were in a Python list, this would be trivial: pair index i with index n-1-i. What does that cost you in space?
Hint 2 Every pair combines one node from the first half with one from the second half, taken in opposite orders. How do you find the middle of a linked list in one pass?
Hint 3 Find the middle with slow/fast pointers, reverse the second half in place, then walk the two halves in lockstep β€” each aligned pair is a twin pair. That is O(n) time and O(1) extra space.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.