Skip to content

1171. Remove Zero Sum Consecutive Nodes from Linked List

View on LeetCode

Approach: Prefix-sum map to nodes; when a sum repeats, delete the intervening nodes and clean map entries.

Complexity: O(n) time, O(n) space

js
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var removeZeroSumSublists = function(head) {
    const dummy = new ListNode()
    dummy.next = head

    const map = { 0: dummy }
    let sum = 0

    while (head) {
        sum += head.val
        if (map[sum]) {
            let temp = map[sum].next
            let delSum = sum
            while (temp != head) {
                delSum += temp.val
                delete map[delSum]
                temp = temp.next
            }
            map[sum].next = head.next
        } else {
            map[sum] = head
        }
        head = head.next
    }

    return dummy.next
};