3

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?

Vishrut Jha
  • 74
  • 1
  • 1
  • 9
  • 1
    As a hint, you have a "Real example" to work with. So don't worry about whether the problem itself is np-hard in general or what-not, you can always brute force and calculate your way while iterating through the nodes. Keep a track of *all* possible sums upto each node, and eliminate entire chains if a sum reaches 0 during iteration. – Paritosh Singh Aug 23 '19 at 06:14
  • Re: "I'm unable to create subsets which contain the consecutive elements that add up to `0`. As it is an `NP-Complete problem`": This is not correct. Finding *arbitrary subsets* that sum to zero is NP-complete; but finding *contiguous sublists* that sum to zero can be done in O(n^2) time. (Also, I mean, even NP-complete problems can be solved; it's just that *if the inputs get too big* then it will take too long.) – ruakh Aug 23 '19 at 18:29

1 Answers1

2

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
Selcuk
  • 57,004
  • 12
  • 102
  • 110