LeetCode 1171 - Remove Zero Sum Consecutive Nodes From Linked List - Python

preview_player
Показать описание
Solution, explanation, and complexity analysis for LeetCode 1171 in Python

Problem Description:

Code:
Комментарии
Автор

There is a simpler approach. It requires no extra memory as well. Just have two pointers and a sliding window, whenever the current sum equals zero remove the window in O(1). The overall time complexity will still be O(n2) but will require no extra memory also it is easier to implement.
class Solution:
def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(next=head)
left = dummy

while left.next:
right = left.next
cur_sum = 0
while right:
cur_sum += right.val
if cur_sum == 0:
break
right = right.next
if cur_sum == 0:
left.next = right.next
continue
left = left.next
return dummy.next

mufaddaltatiwala
Автор

Did you come up with this solution by yourself, because this problem was really hard for me

berserk.
join shbcf.ru