Remove Zero Sum Consecutive Nodes from Linked List - Problem

Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that 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.

Note that in the examples below, all sequences are serializations of ListNode objects.

Input & Output

Example 1 — Remove Middle Zero Sum
$ Input: head = [1,3,-3,2]
Output: [1,2]
💡 Note: The consecutive nodes 3 and -3 sum to 0, so we remove them. The remaining list is [1,2].
Example 2 — Multiple Removals
$ Input: head = [1,2,-3,3,1]
Output: [3,1]
💡 Note: First remove [1,2,-3] which sums to 0, leaving [3,1]. No more zero-sum sequences exist.
Example 3 — All Nodes Removed
$ Input: head = [1,2,3,-3,-2]
Output: []
💡 Note: Remove [2,3,-3,-2] which sums to 0, leaving [1]. Then remove remaining [1] as it doesn't form zero sum alone.

Constraints

  • The number of nodes in the given linked list is in the range [1, 1000]
  • -1000 ≤ Node.val ≤ 1000

Visualization

Tap to expand
Remove Zero Sum Consecutive Nodes from Linked ListInput: [1, 3, -3, 2]13-323 + (-3) = 0REMOVE12Output: [1, 2]
Understanding the Visualization
1
Input
Linked list [1, 3, -3, 2] with consecutive 3, -3
2
Process
Find consecutive sequences that sum to 0
3
Output
Remove zero-sum sequences, return [1, 2]
Key Takeaway
🎯 Key Insight: Use prefix sums to detect when consecutive sequences sum to zero - repeated prefix sums indicate zero-sum ranges that can be removed efficiently.
Asked in
Facebook 35 Microsoft 25 Google 20
32.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen