Remove Zero Sum Runs
Read the list from the front and build a result list. Each node is added to the end of the result. If the result now ends with a run of nodes, one or more, whose values add up to 0, that whole run is taken out again before the next node is read.
Return the head of the result. For 1 -> 2 -> -3 -> 3 -> 1 the first three nodes cancel out, which leaves 3 -> 1. The list is passed in as head.
Linked lists appear in the tests as the list of their values, like [1,2,3]. Each node is a ListNode with .val and .next; the class is already defined for you.
Example 1
After reading 1, 2 and -3 the result adds up to 0 and is emptied. Then 3 and 1 are added and stay.
Example 2
When -3 is read, the run 3, -3 at the end is taken out. The 4 then joins 1 and 2.
Example 3
First 3, -3 goes. Reading -2 then leaves a run 2, -2 at the end, which goes too.
Constraints
0 <= number of nodes <= 60-100 <= node.val <= 100
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Linked lists problems
- Reverse Groups From the EndHard
- Reverse Nodes in K-GroupHard
- Smallest TurnHard
- Subtract Two NumbersHard
- Swap Neighboring BlocksHard
- Alternating SumBeginner
- Are the Lists EqualBeginner
- Average of the ValuesBeginner