LeetCode 1171. Remove Zero Sum Consecutive Nodes from LinkedList
Question
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.
Solution
We need to maintain the hashmap to record the prefix sum to ListNode.
- if we didn’t seen it before, just record.
- otherwise, it shows the range sum between it would be zero, and we have to move our current pointer, at the end, we can skip the range we find.
Code
1 | // time:O(n) space:O(n) |