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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code