Problem Description
Given the head of an even length linked list, each node at index i (0-indexed) forms a twin with the node at index n-1-i. The twin sum of a pair is the sum of the node values. The task is to return the maximum twin sum among all twin pairs in the linked list.
Key Insights
- The linked list has an even number of nodes.
- The first half of the list pairs with the reversed second half of the list.
- By reversing the second half, the twin pairs can be iterated in one pass simultaneously.
- Use the two-pointer technique (slow and fast) to find the midpoint of the list.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1) (if reversing the second half in-place)
Solution
We can solve the problem by first locating the middle of the list using the slow and fast pointer technique. Once we have the middle, we reverse the second half of the list in-place. Then, we iterate through both halves simultaneously, computing the twin sum for each pair and tracking the maximum sum encountered. This approach avoids extra space for an array and completes the solution in a single pass (after the reverse process).