Created
March 30, 2020 02:02
-
-
Save RP-3/c78f9660778a133fbdeb4dbb5c4d796e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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