#2130

Maximum Twin Sum of a Linked List

Medium
Linked ListTwo PointersStackTwo PointersLinked List
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(1)
💡

Intuition

Time O(n)Space O(1)

By reversing the second half of the linked list, we can directly compute the twin sums without needing extra space for an array. This approach is efficient and leverages the structure of the linked list.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a slow and fast pointer to find the midpoint of the linked list.
  2. 2Step 2: Reverse the second half of the linked list.
  3. 3Step 3: Calculate the twin sums by iterating through the first half and the reversed second half, keeping track of the maximum sum.
solution.py24 lines
1# Full working Python code
2class ListNode:
3    def __init__(self, val=0, next=None):
4        self.val = val
5        self.next = next
6
7def pairSum(head):
8    slow = fast = head
9    while fast and fast.next:
10        slow = slow.next
11        fast = fast.next.next
12    prev = None
13    while slow:
14        temp = slow.next
15        slow.next = prev
16        prev = slow
17        slow = temp
18    max_sum = 0
19    left, right = head, prev
20    while right:
21        max_sum = max(max_sum, left.val + right.val)
22        left = left.next
23        right = right.next
24    return max_sum

Complexity note: The time complexity is O(n) because we traverse the list a constant number of times (finding the midpoint, reversing, and calculating sums). The space complexity is O(1) since we only use a few pointers and do not require extra space proportional to the input size.

  • 1Reversing the second half of the list allows direct comparison with the first half.
  • 2Using pointers efficiently reduces space complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.