377. Remove Zero-Sum Consecutive Nodes

MediumLinked ListPrefix SumHashLinked List

Given the head of a linked list, repeatedly delete consecutive sequences of nodes that sum to 0 until none remain. Return the final list as an array. (After all such removals the answer is unique.)

Input: An array of node values.

Output: Array — the list after all zero-sum removals.

Examples

Example 1
Input: [1,2,-3,3,1]
Output: [3,1]
Explanation: 1+2-3=0 removed, leaving 3,1.
Example 2
Input: [1,2,3,-3,4]
Output: [1,2,4]
Explanation: 3 and -3 cancel.
Example 3
Input: [1,2,3,-3,-2]
Output: [1]
Explanation: Trailing nodes cancel to leave 1.

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →