FunctionRacerProblemsRace

Remove Zero Sum Runs

HardLinked listsPython, JavaScript, TypeScript, Java, C++

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

head [1,2,-3,3,1]
returns [3,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

head [1,2,3,-3,4]
returns [1,2,4]

When -3 is read, the run 3, -3 at the end is taken out. The 4 then joins 1 and 2.

Example 3

head [1,2,3,-3,-2]
returns [1]

First 3, -3 goes. Reading -2 then leaves a run 2, -2 at the end, which goes too.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Linked lists problems