<AI/>
enru
Все статьи

Maximum twin sum of a linked list

LeetCode 2130: Find the maximum twin sum in a linked list using an array, a stack, or by reversing half of the list in place.

Сложность
Средняя
Автор
Denis Kolpakov
Опубликовано
Темы
#linked list#two pointers#stack
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

Implement a function that finds the maximum twin sum of a linked list.

The twin of the i-th node is the node with index n - i - 1, where 0 <= i <= n / 2 - 1. In other words, the twin of the first node is the last node, the twin of the second one is the second-to-last, and so on.

Constraints

  • The list always has an even number of nodes
  • The number of nodes is in the range from 2 to 100 000
  • Node values are in the range from 1 to 100 000

Examples

Input: [5,4,2,1]

Answer: 6

Explanation: The list has 2 pairs of twins: [5, 1] and [4, 2]. Both pairs sum up to 6.

Converting to an array

The main difficulty of this problem is the linked list itself: we don't know its length and can't quickly access nodes by index, so we can't quickly find the twin of the current node.

The first idea is to give up on the linked list in favour of an array. That's easy: we go through the whole list once and copy all values into an array. With an array at hand, finding twins is trivial, and the problem boils down to finding the maximum among the twin sums.

typescript
import { ListNode } from './ListNode';
 
export function pairSumSlice(head: ListNode): number {
  let list: number[] = [head.val];
 
  // Walk through the list and fill the array with values
  for (let cur = head.next; cur !== null; cur = cur.next) {
    list.push(cur.val);
  }
 
  let res = 0;
 
  // Find the maximum twin sum
  for (let i = 0; i < Math.floor(list.length / 2); i++) {
    let j = list.length - i - 1;
    res = Math.max(res, list[i] + list[j]);
  }
 
  return res;
}

Complexity Analysis

Time Complexity

We iterate over all elements twice: once to build the array and once to compute the sums.

The overall complexity is O(n).

Space Complexity

O(n), since we allocate memory to store the list as an array.

Stack approach

We can improve the solution by saving memory: there's no need to turn the whole list into an array. It's enough to push the first half of the list onto a stack and then walk through the second half, popping the twin of each next node from the stack.

But this raises another problem: as mentioned, the main limitation is that we don't know the length of the list, so we can't immediately tell where its middle is. We can get around this with a little trick using two pointers:

  • currentListElement moves through the list one node at a time.
  • oddElementList moves two nodes at a time. In a linked list this looks like:
typescript
oddElementList = oddElementList.next.next;

So when oddElementList reaches the end of the list, currentListElement points to the beginning of the second half.

After that, all that's left is to walk currentListElement to the end of the list, popping the twin of each node from the stack and tracking the maximum sum.

typescript
import { ListNode } from './ListNode';
 
export function pairSumStack(head: ListNode): number {
  let stack: number[] = [];
  let currentListElement: ListNode | null = head;
  let oddElementList: ListNode | null = head;
 
  // Push the first half of the list onto the stack
  while (oddElementList !== null && oddElementList.next !== null) {
    stack.push(currentListElement!.val);
    currentListElement = currentListElement!.next;
    oddElementList = oddElementList.next.next;
  }
 
  let res = 0;
 
  // Compare elements from the end of the first half with the second half
  while (currentListElement !== null) {
    res = Math.max(res, currentListElement.val + stack.pop()!);
    currentListElement = currentListElement.next;
  }
 
  return res;
}

Complexity Analysis

Time Complexity

We iterate over all elements once.

The overall complexity is O(n).

Space Complexity

O(n), since we allocate memory to store elements on the stack.

Reversing half of the list

Most likely, though, the problem intends us not to use other data structures (even though there's no explicit restriction). So let's try to solve it using linked lists only.

To find twins quickly, we can reverse part of the list. For that we write a simple function reverseList (the reversal happens in place, without creating a new list).

As with the stack, we don't need to reverse the whole list, just one half of it. The final solution is very similar to the stack-based one, except that instead of a stack we use the second half of the list reversed.

This solution is more memory-efficient, since the reversal happens in place and doesn't need extra space for an array or a stack.

typescript
import { ListNode } from './ListNode';
 
export function pairSum(head: ListNode): number {
  let firstHalfList: ListNode | null = head;
  let oddElementList: ListNode | null = head;
 
  // Find the middle of the list
  while (oddElementList !== null && oddElementList.next !== null) {
    firstHalfList = firstHalfList!.next;
    oddElementList = oddElementList.next.next;
  }
 
  // Reverse the second half of the list
  let revers: ListNode | null = reverseList(firstHalfList);
 
  let maxSum = 0;
  // Compare the elements
  while (revers !== null) {
    maxSum = Math.max(maxSum, head.val + revers.val);
    head = head.next!;
    revers = revers.next;
  }
 
  return maxSum;
}
 
function reverseList(head: ListNode | null): ListNode | null {
  let newHead: ListNode | null = null;
 
  while (head !== null) {
    let next: ListNode | null = head.next;
    head.next = newHead;
    newHead = head;
    head = next;
  }
 
  return newHead;
}

Complexity Analysis

Time Complexity

We only need to iterate over the input list.

The overall complexity is O(n).

Space Complexity

With half of the list reversed in place, the additional memory is O(1).