Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Remove Zero Sum Consecutive Nodes from Linked List

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1171" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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. (Note that in the examples below, all sequences are serializations of ListNode objects.) Example 1: Input: head = [1,2,-3,3,1] Output: [3,1] Note: The answer [1,2,1] would also be accepted. Example 2: Input: head = [1,2,3,-3,4] Output: [1,2,4] Example 3: Input: head = [1,2,3,-3,-2] Output: [1] Constraints: The given linked list will contain between 1 and 1000 nodes. Each node in the linked list has -1000 <= node.val <= 1000.

Explanation

Here's a solution to the problem:

  • Prefix Sum and Hash Map: Calculate the prefix sum as we traverse the linked list. Store each prefix sum and its corresponding node in a hash map.
  • Zero-Sum Sequence Detection: If a prefix sum repeats, it means the nodes between the first occurrence and the current node sum to zero. Remove these nodes.
  • Iterative Deletion: Repeat the process until no more zero-sum sequences are found.

  • Time Complexity: O(n), where n is the number of nodes in the linked list. Space Complexity: O(n) in the worst case, where n is the number of nodes (for the hash map).

Code

    class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def removeZeroSumSublists(head: ListNode) -> ListNode:
    """
    Removes consecutive sequences of nodes that sum to 0 from a linked list.
    """
    dummy = ListNode(0)
    dummy.next = head
    prefix_sum = 0
    sum_map = {0: dummy}  # Store prefix sum and corresponding node

    curr = head
    while curr:
        prefix_sum += curr.val

        if prefix_sum in sum_map:
            # Remove nodes that sum to zero
            prev = sum_map[prefix_sum]
            temp_sum = prefix_sum
            temp_node = prev.next
            while temp_node != curr:
                temp_sum += temp_node.val
                del sum_map[temp_sum]
                temp_node = temp_node.next

            prev.next = curr.next
        else:
            sum_map[prefix_sum] = curr

        curr = curr.next

    return dummy.next

More from this blog

C

Chatmagic blog

2894 posts