Remove Zero Sum Consecutive Nodes from Linked List

MediumLinked Listprefix sum

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given the head of a linked list of integers, delete runs of consecutive nodes whose values sum to 0, and return the head of what remains ([] if nothing remains). Because different deletion orders can leave different lists, use this exact procedure: read the nodes **left to right**, appending each one to a result list. Immediately after each append, if some **suffix** of the result list sums to 0, delete that suffix (there is at most one such suffix, since the result never contains a zero-sum run before this step). Continue with the next input node. Tracking prefix sums of the result list in a hash map makes each step amortized O(1).

Examples

Input: head = [1,2,-3,3,1]
Output: [3,1]
After appending -3 the whole result [1,2,-3] sums to 0 and is deleted; then 3 and 1 are appended.
Input: head = [1,2,3,-3,4]
Output: [1,2,4]
Appending -3 makes the suffix [3,-3] sum to 0, so it is removed.
Input: head = [1,2,3,-3,-2]
Output: [1]
First [3,-3] is removed, leaving [1,2]; then appending -2 makes [2,-2] sum to 0.

Constraints

  • 1 <= number of nodes <= 1000
  • -1000 <= Node.val <= 1000

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More prefix sum problems