Remove Zero Sum Consecutive Nodes from Linked List Problem
Description
LeetCode Problem 1171.
Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.
(Note that in the examples below, all sequences are serializations of ListNode objects.)
Example 1:
Input: head = [1,2,-3,3,1]
Output: [3,1]
Note: The answer [1,2,1] would also be accepted.
Example 2:
Input: head = [1,2,3,-3,4]
Output: [1,2,4]
Example 3:
Input: head = [1,2,3,-3,-2]
Output: [1]
Constraints:
- The given linked list will contain between
1and1000nodes. - Each node in the linked list has
-1000 <= node.val <= 1000.
Solution
Approach: Prefix Sums, Jump to the Last Equal Sum
A run of consecutive nodes sums to 0 exactly when the prefix sum before the run equals the prefix sum at its end. So equal prefix sums mark everything in between as removable.
We put a dummy node with value 0 in front of the head, so that a run starting at the head (prefix sum 0) is handled like any other. Then two passes:
- Walk the list and record, for every prefix sum, the last node where it occurs.
- Walk again from the dummy. At node
curwith prefix sums, everything aftercurup tolast[s]sums to0, so setcur.next = last[s].next, skipping all of it in one step, and continue from there.
Jumping to the last node with the same sum removes the longest zero-sum stretch at once, so no zero-sum run is left over afterwards: each prefix sum appears only once in the final list. If no later node has the same sum, last[s] is cur itself and nothing is skipped.
The answer is dummy.next. Several results can be valid (for [1,2,-3,3,1], both [3,1] and [1,2,1] are accepted), and this method produces one of them.
Complexity: O(n) time and O(n) space for the hash map.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(0, head) # prefix sum 0 before the first node
# Pass 1: for each prefix sum, the LAST node where it occurs.
last = {}
s, cur = 0, dummy
while cur:
s += cur.val
last[s] = cur
cur = cur.next
# Pass 2: everything after cur up to last[s] sums to 0, so jump straight past it.
s, cur = 0, dummy
while cur:
s += cur.val
cur.next = last[s].next
cur = cur.next
return dummy.next