-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path1171.remove-zero-sum-consecutive-nodes-from-linked-list.py
55 lines (46 loc) · 1.59 KB
/
1171.remove-zero-sum-consecutive-nodes-from-linked-list.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#
# @lc app=leetcode id=1171 lang=python3
#
# [1171] Remove Zero Sum Consecutive Nodes from Linked List
#
# @lc code=start
# TAGS: Hash Table, Linked List
from typing import Optional
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
# Cleaner Code
# Time and Space: O(N)
def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:
head = ListNode(0, head)
node, prefix, seen = head, 0, {}
while node:
prefix += node.val
if prefix in seen:
# Detect the sum to 0 => trim the nodes and restart from head.
seen[prefix].next = node.next
node, prefix, seen = head, 0, {}
continue
seen[prefix] = node
node = node.next
return head.next
# Slightly more optimize.
# Instead of restarting from head, we delete dict. This requires OrderedDict()
# Time and Space: O(N)
def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:
head = ListNode(0, head)
node, prefix, seen = head, 0, collections.OrderedDict()
while node:
prefix += node.val
last = seen.get(prefix, node)
while prefix in seen:
# delete last element in seen (everything seen between last <-> node)
seen.popitem()
seen[prefix] = last
last.next = node.next
node = node.next
return head.next
# @lc code=end