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: [1]
💡 Note: Remove [2,3,-3,-2] which sums to 0, leaving [1]. The single node [1] cannot be removed as it doesn't sum to 0.

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 INPUT Linked List Structure: 1 3 -3 2 Prefix Sum Table: Node Prefix Sum 1 1 3 4 -3 1 (repeat!) 2 3 head = [1, 3, -3, 2] ALGORITHM STEPS 1 Init Hash Map Store prefix sum 0 with dummy node 2 First Pass Calculate prefix sums Map: sum --> node 3 Detect Zero Sum Same prefix sum = zero sum sequence exists 4 Second Pass Skip nodes between repeated prefix sums Zero Sum Detection: 3 + (-3) = 0 Remove nodes 3 and -3 3, -3 = removed FINAL RESULT Cleaned Linked List: 1 2 NULL Nodes with value 3 and -3 were removed (sum = 0) Transformation: [1, 3, -3, 2] --> [1, 2] OUTPUT [1, 2] OK - No zero-sum sequences Key Insight: If two nodes have the same prefix sum, all nodes between them sum to zero. Using a hash map to store prefix sums allows O(n) detection and removal of zero-sum sequences. The map stores the last occurrence of each prefix sum to handle overlapping sequences correctly. TutorialsPoint - Remove Zero Sum Consecutive Nodes from Linked List | Hash Map - Prefix Sum Optimization
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