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 1 and 1000 nodes.
Each node in the linked list has -1000 <= node.val <= 1000.
Solutions
Solution 1: Prefix Sum + Hash Table
If two prefix sums of the linked list are equal, it means that the sum of the continuous node sequence between the two prefix sums is $0$, so we can remove this part of the continuous nodes.
We first traverse the linked list and use a hash table $last$ to record the prefix sum and the corresponding linked list node. For the same prefix sum $s$, the later node overwrites the previous node.
Next, we traverse the linked list again. If the current node $cur$ has a prefix sum $s$ that appears in $last$, it means that the sum of all nodes between $cur$ and $last[s]$ is $0$, so we directly modify the pointer of $cur$ to $last[s].next$, which removes this part of the continuous nodes with a sum of $0$. We continue to traverse and delete all continuous nodes with a sum of $0$.
Finally, we return the head node of the linked list $dummy.next$.
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the linked list.
1 2 3 4 5 6 7 8 91011121314151617181920
# Definition for singly-linked list.# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclassSolution:defremoveZeroSumSublists(self,head:Optional[ListNode])->Optional[ListNode]:dummy=ListNode(next=head)last={}s,cur=0,dummywhilecur:s+=cur.vallast[s]=curcur=cur.nexts,cur=0,dummywhilecur:s+=cur.valcur.next=last[s].nextcur=cur.nextreturndummy.next
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funcremoveZeroSumSublists(head*ListNode)*ListNode{dummy:=&ListNode{0,head}last:=map[int]*ListNode{}cur:=dummys:=0forcur!=nil{s+=cur.Vallast[s]=curcur=cur.Next}s=0cur=dummyforcur!=nil{s+=cur.Valcur.Next=last[s].Nextcur=cur.Next}returndummy.Next}