Remove Zero Sum Consecutive Nodes from Linked List

Given the head of a linked list, repeatedly delete consecutive sequences of nodes whose values sum to 0 until there are no such sequences.

After doing so, return the head of the final linked list. You may return any such answer.

Example 1
[1] -> [2] -> [-3] -> [3] -> [1] -> null
---
[3] -> [1] -> null
Inputhead = [1,2,-3,3,1]
Output[3,1]
Deleting the consecutive sequence [1, 2, -3] leaves [3, 1]; the answer [1, 2, 1] would also be accepted.
Example 2
[1] -> [2] -> [3] -> [-3] -> [4] -> null
---
[1] -> [2] -> [4] -> null
Inputhead = [1,2,3,-3,4]
Output[1,2,4]
The consecutive sequence [3, -3] sums to 0, so it is removed to produce [1, 2, 4].

Constraints

  • The given linked list will contain between 1 and 1000 nodes.
  • Each node in the linked list has -1000 <= node.val <= 1000.

Asked at 6 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate