You get the head of a singly linked list with an even number of nodes, n. Number the nodes from 0. Node i and node n − 1 − i are twins: the first node pairs with the last, the second with the second to last, and so on until the two halves meet.
A twin sum is the value of a node plus the value of its twin. Return the largest twin sum in the list.
Example 1
Input: head = [3, 8, 1, 6, 2, 5] Output: 10 Why: the twin sums are 3 + 5 = 8, 8 + 2 = 10 and 1 + 6 = 7
2 more examples and the constraints
Example 2
Input: head = [2, 9, 4, 4] Output: 13 Why: 2 + 4 = 6 and 9 + 4 = 13
Example 3
Input: head = [6, 6] Output: 12 Why: the two nodes are twins of each other
Constraints
- The number of nodes is even, between 2 and 100,000
- 1 ≤ each node's value ≤ 100,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Copy into an arrayO(n)
- Stack of valuesO(n)
- Reverse the second halfO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Extra memory for 100,000 nodes | Verdict |
|---|---|---|---|
| Copy into an array | O(n) | Simple; stores every value | |
| Stack of values | O(n) | Same memory, same idea | |
| Reverse the second half | O(n) | Best; constant extra memory |
n = number of nodes. All three are linear in time; they differ in memory.
Edge cases to test
- Only two nodes. [6, 6] has one twin pair, so the answer is 12.
- Largest values. Two nodes of 100,000 sum to 200,000, which still fits in a 32-bit int.
- Best pair in the middle. [1, 5, 5, 1]: the inner pair wins, so check every pair, not only the outer one.
- Every sum the same. [1, 2, 3, 4, 5, 6, 7, 8] gives 9 for every pair.
Common mistakes
- Stopping
slowone node early, so the halves are uneven and the wrong nodes pair up. - Losing the rest of the list while reversing because
slow.nextwas overwritten before it was saved. - Walking all n nodes in the stack approach and counting every pair twice.
How to talk through it
- 1Clarify. The length is always even, and values are positive? May I change the list?
- 2Start simple. Copy the values into an array and use two pointers from both ends: O(n) time, O(n) space.
- 3Name the obstacle. The list cannot be read backwards. Reversing the second half fixes that without extra memory.
- 4Code it in three parts. Find the middle with slow and fast, reverse from slow, then walk both halves.
- 5Test out loud. Run the two-node case and one where the best pair is in the middle.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?