MrainW's Home

All things come to those who wait!

0%

LeetCode 1171. Remove Zero Sum Consecutive Nodes from Linked List

Question

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.)

https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public ListNode removeZeroSumSublists(ListNode head) {
int preFix = 0;
ListNode dummy = new ListNode(0);
dummy.next = head;
Map<Integer, ListNode> map = new HashMap<>();
map.put(0, dummy);
for(ListNode i = dummy; i != null; i= i.next){
preFix += i.val;
map.put(preFix, i);
}
preFix = 0;
for(ListNode i = dummy; i != null; i = i.next){
preFix += i.val;
i.next = map.get(preFix).next;
}
return dummy.next;
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Welcome to my other publishing channels