Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save RP-3/c78f9660778a133fbdeb4dbb5c4d796e to your computer and use it in GitHub Desktop.
Save RP-3/c78f9660778a133fbdeb4dbb5c4d796e to your computer and use it in GitHub Desktop.
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
var removeZeroSumSublists = function(head) {
const array = [];
let curr = head;
while(curr){
array.push(curr.val);
curr = curr.next;
}
const result = [];
let [total, seenAt] = [0, new Map()];
for(let i=0; i<array.length; i++){
total+=array[i];
result.push(array[i]);
if(total === 0) [seenAt, result] = [new Map(), []];
else if(seenAt.has(total)){
const [endIndex, totalAfterCleaning] = [seenAt.get(total), total];
while(result.length -1 > endIndex){
const removed = result.pop();
total-=removed;
seenAt.delete(total);
}
seenAt.set(totalAfterCleaning, endIndex);
}else{
seenAt.set(total, result.length-1);
}
}
if(!result.length) return null;
const rtn = new ListNode(result[0]);
let tail = rtn;
for(let i=1; i<result.length; i++){
tail.next = new ListNode(result[i]);
tail = tail.next;
}
return rtn;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment