Problem 581
Remove Zero Sum Consecutive Nodes
Medium · 20 pts · Linked List, Hash Table, Prefix Sum
Problem
Walk through a linked list from head to tail, building a result list. Append each node to the result; if after appending, some run of nodes at the end of the result sums to 0, delete that whole run at once. After this, no run at the end ever sums to 0, so the run to delete is always unique. Print the final list. Keep the prefix sums of the result in a stack plus a set: a repeated prefix sum means the nodes after its first occurrence add up to 0.
Input
The first line contains N, the number of nodes. The second line contains the N node values from head to tail.
Output
Print the node values of the resulting list from head to tail, separated by spaces, or EMPTY if the list has no nodes.
Constraints
1 <= N <= 1000; -1000 <= value <= 1000
Example input
5 1 2 -3 3 1
Example output
3 1
Explanation
For 1 2 -3 3 1, after appending -3 the result 1 2 -3 sums to 0, so all three nodes are deleted. Then 3 and 1 are appended and never form a zero-sum run, so the answer is 3 1.