โ†‘ Top

Print All Zero Sum Subarray

ullas kunder

Designer & Developer

๐Ÿง  Print All Zero-Sum Subarrays in an Array

โœ… Problem Statement

Given an array of integers, find and print all contiguous subarrays whose sum is zero.


๐Ÿงฉ Example

Input: [3, 4, -7, 3, 1, 3, 1, -4, -2, -2]
Output:
  Subarray found from Index 0 to 2
  Subarray found from Index 1 to 3
  Subarray found from Index 2 to 4
  Subarray found from Index 6 to 9
  ...and more

๐Ÿ” Approach 1: Brute-Force (O(nยฒ))

  • For every starting index, try all possible subarrays
  • Keep a running sum
  • If at any point, the sum is zero โ†’ print the subarray's index range

๐Ÿ Python Code

def print_all_zero_sum_sublists_brute(nums):
    for i in range(len(nums)):
        total = 0
        for j in range(i, len(nums)):
            total += nums[j]
            if total == 0:
                print(f"Subarray found from Index {i} to {j}")

๐Ÿ”Ž When to Use

  • Simple to understand
  • Not suitable for large arrays

โšก Approach 2: Prefix Sum with HashMap (O(n))

This method uses a prefix sum and a dictionary to track previous sums. If the same prefix sum appears again, it means the subarray in between sums to zero.

๐Ÿ’ก Idea

  • Maintain a cumulative prefix_sum
  • Store all indices where a particular prefix_sum has occurred
  • If prefix_sum repeats, all subarrays between previous and current index are zero-sum

๐Ÿ Python Code

def insert(d, key, value):
    d.setdefault(key, []).append(value)

def print_all_zero_sum_sublists(nums):
    d = {}
    insert(d, 0, -1)  # For subarrays starting from index 0
    total = 0

    for i in range(len(nums)):
        total += nums[i]

        if total in d:
            for start_index in d[total]:
                print(f"Subarray found from Index {start_index + 1} to {i}")
        insert(d, total, i)

๐Ÿงช Trace Example

Input: [3, 4, -7, 3, 1, 3, 1, -4, -2, -2]

IndexValuePrefix SumSeen at IndicesNew Subarrays
033โ€”โ€”
147โ€”โ€”
2-70[-1](0, 2)
333[0](1, 3)
414โ€”โ€”
537[1](2, 5)
618โ€”โ€”
7-44[4](5, 7)
8-22โ€”โ€”
9-20[-1, 2](0, 9), (3, 9)

๐Ÿ“ Summary

ApproachTimeSpaceNotes
Brute-forceO(nยฒ)O(1)Easy to write, slow for large n
Prefix HashingO(n)O(n)Efficient and elegant