InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Linked List

Maximum Twin Sum of a Linked List

medium Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug