Leetcode 1171: Remove Zero Sum Consecutive Nodes from Linked List

grid47
grid47
Exploring patterns and algorithms
Jul 12, 2024 6 min read

Given the head of a linked list, iteratively remove all consecutive subsequences of nodes whose sum is 0. Return the modified linked list after all such subsequences have been removed. You may return any valid result.
Problem
Approach
Steps
Complexity
Input: The input is the head of a singly linked list.
Example: Input: head = [2,-2,3,1,-1,4,-4,5]
Constraints:
• 1 <= length of linked list <= 1000
• -1000 <= node.val <= 1000
Output: Return the head of the modified linked list with all zero-sum subsequences removed.
Example: Output: [5]
Constraints:
• The output linked list should not contain any zero-sum consecutive subsequences.
Goal: Iteratively remove zero-sum consecutive subsequences from the linked list.
Steps:
• 1. Create a dummy node and link it to the head of the list.
• 2. Traverse the list while maintaining a prefix sum.
• 3. Use a hash map to track nodes corresponding to each prefix sum.
• 4. When a prefix sum is encountered again, remove all nodes in the subsequence between the two occurrences.
• 5. Return the updated list starting from the dummy node’s next pointer.
Goal: The input linked list contains integer values, and the removal should preserve non-zero-sum segments.
Steps:
• Each node's value lies in the range [-1000, 1000].
• The length of the list is between 1 and 1000.
Assumptions:
• Input is always a valid singly linked list.
• Zero-sum subsequences can span multiple nodes.
Input: Input: head = [1,3,-3,4,5,-4]
Explanation: The sequence [3,-3] sums to 0 and is removed. Then [4,5,-4] sums to 0 and is also removed. The final list is [1].

Input: Input: head = [2,3,-5,5,-2,1]
Explanation: The sequence [2,3,-5] sums to 0. Removing it leaves [5,-2,1]. No further zero-sum sequences exist. The result is [5,-2,1].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus