Maximum Twin Sum of a Linked List — LeetCode 2130 Python Solution

MediumStackLinked ListTwo Pointers
Problem
#2130
Reading time
3 min

The problem

In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1. For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2.

Example

Input
head = [5,4,2,1]
Output
6
Explanation
Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.

Python solution

Python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def pairSum(self, head: Optional[ListNode]) -> int:
        s = []
        while head:
            s.append(head.val)
            head = head.next
        n = len(s)
        return max(s[i] + s[-(i + 1)] for i in range(n >> 1))

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the number of nodes in the linked list auxiliary

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 2130. Maximum Twin Sum of a Linked List is filed here because LeetCode tags it Linked List, which is the vocabulary this hub collects.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

On a study list

This problem is on LeetCode 75.

Frequently asked questions

How hard is LeetCode 2130. Maximum Twin Sum of a Linked List?
LeetCode 2130. Maximum Twin Sum of a Linked List is rated Medium on LeetCode.
What is the time complexity of LeetCode 2130. Maximum Twin Sum of a Linked List?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2130. Maximum Twin Sum of a Linked List?
The Python solution on this page uses O(n), where n is the number of nodes in the linked list auxiliary space.
What topics does LeetCode 2130. Maximum Twin Sum of a Linked List cover?
LeetCode 2130. Maximum Twin Sum of a Linked List is tagged Stack, Linked List and Two Pointers on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview