Search code examples
pythonalgorithmlinked-listsubset-sumnp-complete

How to delete consecutive elements in a linked list which add up to 0


I'm writing a Python code to delete those consecutive elements in a linked list, which add up to 0

The linked list is defined as follows:

class Node:
    def __init__(self, val, next=None):
        self.value = val
        self.next = next

node = Node(10)
node.next = Node(5)
node.next.next = Node(-3)
node.next.next.next = Node(-3)
node.next.next.next.next = Node(1)
node.next.next.next.next.next = Node(4)
node.next.next.next.next.next.next = Node(-4)

From the above data, 5 -> -3 -> -3 -> 1 as well as 4 -> -4 needs to be eliminated as they add up to 0.

After iterating through the elements, as in

def removeConsecutiveSumTo0(node):
    start = node
    while start:
        mod = False
        total = 0
        end = start

        while end:
            total += end.value
            if total == 0:
                start = end
                mod = True
                break
            end = end.next

        if mod == False:
            res = start

        start = start.next

    return res

node = removeConsecutiveSumTo0(node)
while node:
    print (node.value, end=' ')
    node = node.next
# 10 (Expected output)

I'm unable to create subsets which contain the consecutive elements that add up to 0. As it is an NP-Complete problem as discussed here and here. How can I devise the algorithm to find the solution?


Solution

  • You may try recursion, or nested loops as you should try starting from each node while calculating the sum. A naive implementation could be as follows:

    def removeConsecutiveSumTo0(node):
      start = node
      while start.next:
        total = 0
        cur = start.next
        while cur:
          total += cur.value
          if total == 0:
            start.next = cur.next
            break
          cur = cur.next
        else:
          start = start.next